pthread C++ in Centos no run -


this code:

void* task1(void* unused) {     try {                      cout << "run thread" << endl;          }catch (const char* msg) {       cout << msg << endl;     }     }  int main(int argc, char *argv[]) {        try {       pthread_t thread_id;           int res = pthread_create(&thread_id, null, &task1, null);       cout << res << std::endl;          exit(exit_success);           }catch (const char* msg) {       cout << msg << endl;     }  } 
  • in ubuntu code run.
  • in centos code not run, if use pthread_join(thread_id, null); code run can waiting pthread complete. try pthread_tryjoin_np code not run.
  • please me run code in centos no wating

if program main() exits before thread starts (and runs point cout << ...), thread terminated , not continue run.

i.e. need wait pthread_join() before main() exits.

the case in ubuntu pure coincidence, thread manages print line before terminated c++ runtime after main() exits.

if not want wait because want start multiple threads, can use thread pool (array of threads). first start of them, , pthread_join() wait of them finish.

also, if pthread_join() blocks although thread terminated, make sure created thread joinable. default, make sure not explicitly set thread attributes pthread_create_detached.

to absolutely sure, can provide thread create attributes explicitly , ensure thread created joinable:

pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, pthread_create_joinable); pthread_create(&thread_id, &attr, &task1, null); pthread_attr_destroy(&attr); pthread_join(thread_id, null); 

(error handling not included)


Comments