【问题标题】:C++ Kill waiting std::threadC++ 杀死等待 std::thread
【发布时间】:2016-10-01 12:49:59
【问题描述】:

我的辅助线程侦听通道兔子,并希望在我调用方法 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() 但不工作。 我怎样才能残酷地杀死这个过程?

【问题讨论】:

  • 你真的应该避免杀死它(资源泄漏等)
  • 你可以使用no-blocking接收功能吗?每个像样的库都应该有一个 block_for 函数
  • @deviantfan 我知道,但如果我想怎么做?

标签: c++ multithreading stdthread


【解决方案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
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多