线程意外结束.c++



我正试图抓住pthreads。我看到有些人也有意想不到的pthread行为,但似乎没有一个问题得到回答。

下面的代码应该创建两个线程,一个依赖于另一个。我读到每个线程都会在它们的堆栈中创建变量(不能在线程之间共享),使用全局指针是一种让线程共享值的方法。一个线程应该打印当前的迭代,而另一个线程休眠10秒。最终的预期是10次迭代。使用断点,似乎脚本只是在

处终止。
while (*pointham != "cheese"){

也可能是我没有正确地利用代码块调试功能。任何指针(哈哈哈哈)都会有帮助。

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <string>
using namespace std;
string hamburger = "null";
string * pointham = &hamburger;
void *wait(void *)
{
    int i {0};
    while (*pointham != "cheese"){
        sleep (1);
        i++;
        cout << "Waiting on that cheese " << i;
    }
    pthread_exit(NULL);
}
void *cheese(void *)
{
    cout << "Bout to sleep then get that cheese";
    sleep (10);
    *pointham = "cheese";
    pthread_exit(NULL);
}
int main()
{
   pthread_t threads[2];
   pthread_create(&threads[0], NULL, cheese, NULL);
   pthread_create(&threads[1], NULL, wait, NULL);
   return 0;
}

问题是您启动线程,然后退出进程(从而杀死线程)。您必须等待线程退出,最好使用pthread_join函数。

如果你不想连接所有的线程,你可以在线程中调用pthread_exit(),而不是从main()返回。

但是请注意手册中的BUGS部分:

   Currently, there are limitations in the kernel implementation logic for
   wait(2)ing on a stopped thread group with a dead thread  group  leader.
   This  can manifest in problems such as a locked terminal if a stop sig‐
   nal is sent to a foreground  process  whose  thread  group  leader  has
   already called pthread_exit().

根据本教程:

如果main()在它创建的线程之前完成,并使用pthread_exit()退出,其他线程将继续执行。否则,它们将在main()结束时自动终止。

因此,您不应该以语句return 0;结束main函数。但你应该用pthread_exit(NULL);代替。

如果这对你不起作用,你可能需要在这里学习连接线程。

相关内容

最新更新