C++:如何在循环中添加线程但不"pause"循环?
C++: How to add pthreads in a loop but not "pause" the loop?
我正在学习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函数。
相关文章:
- 为什么我不能在 while 循环中创建线程?
- 重新启动后,线程无法在 while 循环中再次运行
- 接受线程 C++ 套接字中的函数循环
- 使用 shared_ptr 在中断时结束多线程循环
- Qt 在另一个线程中无限循环
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 目标C++,如何在后台线程中使用运行循环?
- 在 While 循环中重用对象的多线程
- 在其他线程中循环访问该concurrent_vector时调用 concurrency::concurrent_vect
- C++uWebSockets将事件循环集成到一个线程中
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- for 循环中的线程无法正常工作
- 更好的做法:永远循环线程或连续线程
- Qt的事件循环线程是安全的还是原子的?处理"队列连接"时如何同步?
- 线程:C++ 中无限循环线程的终止
- 英特尔 TBB 并行循环线程 ID
- 在Qt中,当事件循环线程拥有的QObject上的插槽正在执行时,QThread的事件循环是否会阻塞?
- 高频循环/线程定时
- 当循环/线程断点发生时