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!