0

I am learning pthread but I have one problem. I would like to add a thread inside loop so that the thread function can be implemented separately and the loop doesn't pause till the thread function finished.

Here is my sample code:

void * numbers(void * a){
    cout << "---------------------"<<endl;
    int * args = ( int*) a;
    int sum =0;
    for(int i = 0; i < 1000000000; i++)
    sum++;
}

int main(){

int sum2 = 0;
while(1){
    sum2 = sum2 + 3;
    cout << sum2 << endl;
    int num;
    pthread_t thread_id2;
    pthread_create( &thread_id2, NULL, numbers, (void*) &num);
    void *status1;
    pthread_join( thread_id2, NULL);
}


return -1;
}

The result of the code, as shown below, is not what I want.

3
---------------------
6
---------------------
9
---------------------

My idea is the loop keeps summing up sum2 while thread function "numbers" is running. So the result I need should be something like:

3
6
9
12
-------------------
15
18 and so on

Can anyone help me with this? Thank you!

debug_all_the_time
  • 564
  • 1
  • 5
  • 18
  • 3
    Don't `pthread_join` in the loop. Join blocks the calling thread until the joined thread completes. [Read the `pthread_join` documentation for more details.](http://www.manpages.info/linux/pthread_join.3.html) – user4581301 Feb 04 '16 at 02:07
  • Indeed, pausing the loop is *the entire purpose of `pthread_join`*. (But you do need to call either `pthread_join` or `pthread_detach` at some point, or you'll get a memory leak) – user253751 Feb 04 '16 at 02:10
  • I don't really get your example but it seems o me that what you need is an array of `pthread_t` handles and two loops: The first loop `pthread_create`s all threads in the array and the second `pthread_join`s them again. Between the two loops, you can do whatever needs to be done. – 5gon12eder Feb 04 '16 at 02:34
  • look here for how to run threads and wait for them all to finish http://stackoverflow.com/questions/11624545/how-to-make-main-thread-wait-for-all-child-threads-finish – pm100 Feb 04 '16 at 03:00

1 Answers1

1

call pthread_detach(thread_id2) instead of pthread_join function.

Safwan Ahmed
  • 205
  • 2
  • 7
  • `pthread_detach` won't cut it here. `main` would run through the loop and then exit the program, leaving the still-running threads in a bad position. OP needs to record all of the started threads, then join them after the starting loop all to ensure they all manage to complete before exiting. – user4581301 Feb 04 '16 at 17:12
  • Thanks. But what if I need to return value from the pthread function? Because pthread_detach cannot return the value from the pthread function....What can I use instead of pthread_join( thread_id2, &status1)? – debug_all_the_time Feb 04 '16 at 18:05
  • Call pthread_join at the point where you require the result. It'll wait at that point until the thread will end. And the thread will call pthread_exit at the end. Hope that will help you – Safwan Ahmed Feb 06 '16 at 17:21