9 years, 8 months ago.

Need some help with threads simple application

Need help with threads

Hello,

I am building a small library that creates a thread on its constructor and returns to main thread.

This "worker" thread will just seat on a while (1) reading from a Serial USB (pc) connected to a console. Reads are done via pc.gets(Consolentry,100). Reads not fulfilling a certain format are discarded and the thread goes into an extended Thread::wait to let the main thread make use of the serial console input (potentially).

This worker thread might printf as well to Serial pc for logging.

The main thread, instantiates the class and then goes into a while(1) loop doing other stuff. Potentially reading and writing as well to the console vi Serial pc.

1st Issue: The worker thread will start, change to status Ready and nothing else will happen. Still, worker will never provide a hearbeat telling it is alive. Main never restarts.

2nd Issue: Don't know why, after adding a few printfs here and there, worker will start, will change to state running. Will provide just one heartbeat ( entry into worker) but will never provide exit heartbeat. Then nor main nor worker will do anything again.

Any help appreciated.

Julian

Stubs

main(){
VarStore Store;
pc.printf("back from constructor never reached....\n");
}

Constructor
VarStore::VarStore()
{
    void *MyThis =(void *)this;
    VarCounter=0;
    pc.printf("launching worker \n");
    Thread t(VarStore::Worker,MyThis,osPriorityNormal,DEFAULT_STACK_SIZE,NULL);
    PrintThreadState( t);
    Thread::wait(100);
    PrintThreadState( t);  /* on issue one this status will never get printed */
}

worker thread

void VarStore::Worker(void const *args)
{
    char ConsoleInput[100];
    int ret;
    VarStore *MyThis=(VarStore *)args;
    pc.printf("inside worker \n");                 /* on issue 2, this will be printed. Nothing else below */
    while (1) {
        if(pc.readable()) {
            pc.printf("inside worker  reading input\n");
            pc.gets(ConsoleInput ,100-1);
            ret=MyThis->Set(ConsoleInput);
            pc.printf("got console input %s \n",ConsoleInput);
            if(ret==ERR) Thread::wait(10000);
        }
                pc.printf("inside worker  waiting input\n");
        Thread::wait(500);
    }
}

ok, one lesson learned/step further. Worker will always show in ready when printing status as there can be only one thread running and the main one is printing the state of the worker.....keep working

posted by julian C 18 Aug 2014

Ok I am giving up.

It seems that contrary to some comments, you cannot instantiate a thread from a constructor. Nor even if the member function is static. You need to first create the thread. I did multiple tests, MVP/minimum viable program.... and hit the wall again and again.

posted by julian C 20 Aug 2014
Be the first to answer this question.