【问题标题】:C++: How to add pthreads in a loop but not "pause" the loop?C++:如何在循环中添加 pthreads 但不“暂停”循环?
【发布时间】:2016-02-04 02:01:25
【问题描述】:

我正在学习 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
---------------------

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

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

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

【问题讨论】:

  • 不要在循环中pthread_join。 Join 阻塞调用线程,直到加入的线程完成。 Read the pthread_join documentation for more details.
  • 确实,暂停循环是pthread_join的全部目的。 (但您确实需要在某些时候调用pthread_joinpthread_detach,否则会出现内存泄漏)
  • 我不太明白你的例子,但我觉得你需要的是一个pthread_t句柄数组和两个循环:第一个循环pthread_creates数组中的所有线程和第二个pthread_joins 再次他们。在这两个循环之间,你可以做任何需要做的事情。
  • 查看这里如何运行线程并等待它们全部完成stackoverflow.com/questions/11624545/…

标签: c++ multithreading


【解决方案1】:

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

【讨论】:

  • pthread_detach 不会在这里删减。 main 将运行循环然后退出程序,使仍在运行的线程处于错误位置。 OP 需要记录所有启动的线程,然后在启动循环之后加入它们,以确保它们在退出前都能够完成。
  • 谢谢。但是如果我需要从 pthread 函数返回值怎么办?因为 pthread_detach 无法从 pthread 函数返回值....我可以使用什么来代替 pthread_join(thread_id2, &status1)?
  • 在需要结果的地方调用 pthread_join。它会一直等到线程结束。并且线程最后会调用 pthread_exit。希望对你有帮助
猜你喜欢
  • 2012-03-22
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 2018-03-24
  • 2020-04-15
相关资源
最近更新 更多