我创建了一个线程,并使用条件变量对其进行“调用”(即解锁)处理。

这是基本代码:

#include <iostream>
#include <thread>
#include <condition_variable>

std::condition_variable t1_cond;

void task() {
    std::mutex mtx;
    std::unique_lock<std::mutex> lock{ mtx };

    while (true) {
        t1_cond.wait(lock);
        std::cout << "doing somethings..." << std::endl;
    }
}

int main() {
    int message;
    std::thread t1(task);

    for (int i = 0; i < 3; i++) {
        std::cin >> message;

        t1_cond.notify_one();

    }

    // here I want to kill the t1 thread
    // t1.join() works only if I first release lock, but it seems a weird approch

    return 0;
}

正如您在代码中所看到的,最后,我想“残酷地”杀死线程,即使该线程正在处理(或等待)。

你会怎么做? t1_cond.notify_one();并使用另一个条件变量,如果被标记,则仅返回?

对于基本任务而言,这似乎有点复杂,也许有一些我尚不了解的奇特方式。

最佳答案

正如其他人在评论中指出的那样,不要在线程上进行苛刻的终止。用信号通知它退出,然后等待它完成。

例如,我们可以在线程和main之间使用as全局(或共享)变量。还有其他方法可以做到这一点,例如,它可以工作:

声明一个全局变量。让我们使用atomic,这样我们就不必深入探讨线程之间的缓存一致性的侧面讨论了。

#include <atomic>
std::atomic_bool g_exitCondition;

std::condition_variable t1_cond;

在线程中更改while循环以检查退出条件。
while (g_exitCondition == false) {
    t1_cond.wait(lock);
    if (g_exitCondition == false) {
        std::cout << "doing somethings..." << std::endl;
    }
}
std::cout << "Exiting thread" << std::endl;

然后正确发出信号退出线程并等待它在main中完成:
    g_exitCondition = true;
    t1_cond.notify_all();
    t1.join();

    return 0;
}

关于c++ - 如何杀死由条件变量锁定的线程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58481511/

10-14 10:34
查看更多