c - pthread- creating a new thread each time a method is called -


[this heavy improvment previous question asked. question make more sense on i'm trying do]

i want create program creates new thread each time specific method called. here working code far:

#define number_of_threads   3  pthread_t threads[number_of_threads]; pthread_attr_t attr;  void *busywork(void *t) {    int i;    long tid;    tid = (long)t;     printf("thread %ld running...\n",tid);     // ...     printf("thread %ld completed...\n",tid);     pthread_exit((void*) t); }  void createnewthread(int number){     printf("running createnewthread(%d)\n", number);     pthread_t tid;     int rc = pthread_create( &tid, &attr, busywork, (void *) (long)number);     if (rc) {         printf("error; return code pthread_create() %d\n", rc);         exit(-1);     } }  int main(int argc, char *argv[]) {     int i, rc;      //set thread attributes     pthread_attr_init(&attr);     pthread_attr_setdetachstate(&attr, pthread_create_joinable);      //arbitary amount of calls (my real program call createnewthread() funcion multiple unkown amount of times)     createnewthread(15);     createnewthread(27);     createnewthread(62);     createnewthread(500);     createnewthread(8864);     createnewthread(99999);      //free attributes     pthread_attr_destroy(&attr);      //wait other threads still running     // how can this????     /*for (i=0; i< number_of_threads; i++){         rc = pthread_join( ??? , null); //todo         if (rc){             printf("error: return code pthread_join() %d\n", rc);             exit(-1);         }         printf("main: completed join thread %d\n", i);     }*/      printf("main: program completed. exiting.\n");       pthread_exit(null); // (?) part nessassary on main thread , exit program       return 0; } 

however can see in code there few issues! example, how can wait processes complete code using, not keeeping track of thread number. when thread "busywork" done not clean after self , left orphan process.

one idea had use vector keep track of each thread number , use final join @ end of main. problem array list can large , never shrink though thread complete.

please me find suitable solution these problems.

many thanks!

detach threads, don't join them. before create thread, increment counter protected mutex. right before thread terminates, acquire mutex , decrement counter. know threads done when counter reads zero. can use condition variable make counter waitable if like.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -