终止等待的std::线程

C++ Kill waiting std::thread

本文关键字:线程 std 等待 终止      更新时间:2023-10-16

我的辅助线程监听rabbit通道,并希望在调用stoppllisten()方法时将其从主线程中删除。

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
  }
}