C ++杀掉等待std :: thread

时间:2016-10-01 12:49:59

标签: c++ multithreading stdthread

我的辅助线程侦听通道兔子,并且当我调用方法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()但不工作。 我怎么残忍地杀了这个过程?

1 个答案:

答案 0 :(得分:1)

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

如果您使用的库未提供,则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
  }
}