gpt4 book ai didi

c++ - 如何让 std::thread 停止?

转载 作者:太空宇宙 更新时间:2023-11-04 16:01:59 25 4
gpt4 key购买 nike

我有两个问题。

1) 我想启动一些具有无限循环的功能,以像服务器一样工作,并在单独的线程中检查消息。但是我想在需要时从父线程关闭它。在这种情况下,我很困惑如何std::futurestd::condition_variable。还是创建一些全局变量并从父线程将其更改为 true/false 更好。
2)我想要这样的东西。为什么这个例子在运行时会崩溃?

#include <iostream>
#include <chrono>
#include <thread>

#include <future>

std::mutex mu;
bool stopServer = false;

bool serverFunction()
{

while (true)
{
// checking for messages...
// processing messages

std::this_thread::sleep_for(std::chrono::seconds(1));

mu.lock();

if (stopServer)
break;

mu.unlock();
}

std::cout << "Exiting func..." << std::endl;

return true;
}

int main()
{
std::thread serverThread(serverFunction);

// some stuff

system("pause");

mu.lock();

stopServer = true;

mu.unlock();

serverThread.join();
}

最佳答案

Why this one example crashes during the run time?

当您离开线程的内部循环时,互斥锁处于锁定状态,因此如果您再次使用该互斥锁,父线程可能会永远被阻塞。

你应该使用 std::unique_lock 或类似的东西来避免这样的问题。

关于c++ - 如何让 std::thread 停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42226269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com