gpt4 book ai didi

C++ 终止等待 std::thread

转载 作者:行者123 更新时间:2023-11-30 05:22:09 26 4
gpt4 key购买 nike

我的辅助线程监听 channel 兔子,并希望在我调用方法 stopListen() 时将其从主线程中删除。

void PFClient::startListen()
{
this->stop = false;
this-> t = thread(&PFClient::callback,this);
}

void PFClient::callback()
{
PFAPIResponse* response;
char * temp;
while (!this->stop)
{
try
{

std::string receiver_data = "";
//std::wcout << L"[Callback] oczekiwanie na wiadomość !" << endl;
receiver_data = this->channel->BasicConsumeMessage()->Message()->Body();
temp = &receiver_data[0];
... some operation with received data

void PFClient::stopListen()
{
this->stop = true;
}

信号量无法正常工作,因为它只有在收到下一条消息后才会工作。我尝试 detach(),terminate() 但没有用。我怎样才能残酷地杀死这个过程?

最佳答案

正如我在评论中已经建议的那样,您可以使用无阻塞功能。

如果您使用的图书馆不提供它,那么 async可能是一个有效的选择:

while (this->stop == false) {
auto receiver_data = std::async(/* ... address function and object*/);

// wait for the message or until the main thread force the stop
while (this->stop == false &&
(receiver_data.wait_for(std::chrono::milliseconds(1000) == std::future_status::timeout))
;

if (this->stop == false && receiver_data.vaild() == true) {
// handle the message
}
}

关于C++ 终止等待 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806797/

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