2016-10-01 84 views
1

我的辅助线程侦听通道rabbit,并希望在我调用stopListen()方法时从主线程中删除它。C++杀死等待std ::线程

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

你真的应该避免杀死它(资源泄漏等) – deviantfan

+1

你会用* NO-阻止*接收功能?每个体面的图书馆都应该有* block_for *功能 –

+0

@deviantfan我知道,但是如果我想如何做到这一点? – Jakooop

回答

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

thx,我会试试这个!这是https://github.com/alanxz/SimpleAmqpClient,它是同步方法 – Jakooop