2016-10-01 185 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