c++ - 线程意外结束。 C++

标签 c++ multithreading pointers pthreads sleep

我正在尝试控制 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/

相关文章:

multithreading - 优先级队列的现实示例是什么?

Java ExecutorService : awaitTermination of all recursively created tasks

检查指针数组中的指针是否为空

C++ std::vector 的指针删除和段错误

c++ - Windows Live Messenger "What I' m 收听”功能

c++ - 使用 ffserver 进行 RTMP 流式传输

c++ - 删除 2D 指针矩阵时崩溃 [检测到堆损坏]

c++ - 平整湖泊周围的土地

c++ - 当对共享数据的所有引用都被序列化时,为什么函数是线程安全的?

string - Rust 创建带指针偏移量的字符串