我正在尝试控制 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
功能。
关于c++ - 线程意外结束。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23849639/