终止等待的std::线程
C++ Kill waiting std::thread
我的辅助线程监听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
}
}
相关文章:
- 为什么std::async使用同一个线程运行函数
- 在std::thread中,joinable()然后join()线程安全吗
- 在main()之外初始化std::vector会导致性能下降(多线程)
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 使用 std::string () const 函数启动线程或未来
- 用C++中的std::condition_variable将线程置于死锁中会有风险吗
- 即发即弃 std::线程对象清理自身
- std::mutex 如何防止线程修改?
- std::线程导致程序中止
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- std::cout 来自多个线程
- 简单使用 std::atomic 在两个线程之间共享数据
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 线程 std::调用未知类型,无法专门化函数错误
- 使用 std::chrono::steady_clock 对线程/异步中的代码进行基准测试
- 带有 std::cout 的多线程控制台文本动画
- 线程不是 std c++ 的成员
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 使用 std::condition_variable 触发其他线程.使用哪些互斥锁?
- 使用多线程(std::async、std::thread或?)加速