C++:如何在循环中添加线程但不"pause"循环?

C++: How to add pthreads in a loop but not "pause" the loop?

本文关键字:循环 线程 pause C++ 添加      更新时间:2023-10-16

我正在学习pthread,但我有一个问题。我想在循环中添加一个线程,以便线程函数可以单独实现,并且循环在线程函数完成之前不会暂停。

这是我的示例代码:

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;
}

代码的结果,如下所示,不是我想要的。

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

我的想法是循环在线程函数"数字"运行时不断汇总 sum2。所以我需要的结果应该是这样的:

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

谁能帮我解决这个问题?谢谢!

调用pthread_detach(thread_id2)而不是pthread_join函数。