如何杀死被条件变量锁定的线程?

时间:2019-10-21 07:20:13

标签: c++ multithreading

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

这是基本代码:

#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();并使用另一个条件变量,如果已标记该变量,则仅返回?

对于一项基本任务来说似乎有点复杂,也许还有一些我不知道的奇特方式。

1 个答案:

答案 0 :(得分:3)

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

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

声明一个全局变量。让我们使用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;
}