c++ - Is it acceptable and safe to pthread_join myself? -


i've got setup bit this:

void* work(void*) { while (true) {/*do work*/} return 0;}  class workdoer { private:     pthread_t id; public:     workdoer() { pthread_create(&id, null, work, (void*)this); }     void shutdown() { pthread_join(id, null); /*other cleanup*/ } } 

there's cases shutdown() called main thread, , other cases want call shutdown within thread (returning thread right after).

the documentation pthread_join() says return edeadlk if calling thread same 1 passed.

my question is: okay thing do, , if safe? (thus ignoring join fail, because i'll nicely ending thread in moment anyways?) or, should avoided?

you can call pthread_join() running thread itself, , have found out call handle giving error code. however, there few problems:

  1. it doesn't make sense because join won't join anything. merely tell you doing wrong.
  2. the thread won't exit upon calling pthread_join() on itself.
  3. even if thread exists, state won't cleaned properly. other thread (i.e. application's main thread) should call pthread_join() unless thread created “detached”.

so in other words approach acceptable bug in program.

as solution recommend revisit design , make sure shutdown() called right place , @ right time. after all, name “shutdown” doesn't make lot of sense here because doesn't shutdown thing. merely waiting thread finish , cleans state after happens.

when want end worker thread, either return thread routine or call pthread_exit(). make sure whoever started thread cleans things calling pthread_join().

if want force thread stop, consider using pthread_kill() signal thread or, alternatively, implement sort of message passing can use "tell" thread stop doing whatever doing.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -