C++ p_线程:从多个线程退出
我在程序中创建了两个线程。我想在thread_2函数中终止thread_1,反之亦然,基于标志。我尝试了exit()和pthread_exit(Thread_id),但不起作用。我想通过调用pthread_cancel来取消线程执行,但问题是我无法在pthread_创建之前传递线程id。有什么建议吗?您可以查看C++ p_线程:从多个线程退出,c++,multithreading,pthreads,exit,C++,Multithreading,Pthreads,Exit,我在程序中创建了两个线程。我想在thread_2函数中终止thread_1,反之亦然,基于标志。我尝试了exit()和pthread_exit(Thread_id),但不起作用。我想通过调用pthread_cancel来取消线程执行,但问题是我无法在pthread_创建之前传递线程id。有什么建议吗?您可以查看pthread\u cancel的工作原理 但是,既然您提到了C++,为什么不使用语言特性呢?可以使用条件变量发送一个或多个其他线程的信号 查看它 如果没有C++11,可以使用Boost线
pthread\u cancel
的工作原理
但是,既然您提到了C++,为什么不使用语言特性呢?可以使用条件变量发送一个或多个其他线程的信号
查看它
如果没有C++11,可以使用Boost线程
#include <thread>
#include <condition_variable>
#include <iostream>
using namespace std;
struct workers
{
mutex mx;
condition_variable cv;
bool canceled;
workers() : canceled(false) {}
void thread1()
{
cout << __PRETTY_FUNCTION__ << " start\n";
this_thread::sleep_for(chrono::seconds(2));
{
unique_lock<mutex> lk(mx);
cout << __PRETTY_FUNCTION__ << " signaling cancel\n";
canceled = true;
cv.notify_all();
}
this_thread::sleep_for(chrono::seconds(2));
cout << __PRETTY_FUNCTION__ << " done\n";
}
void thread2()
{
cout << __PRETTY_FUNCTION__ << " start\n";
for(;;)
{
// do some work
unique_lock<mutex> lk(mx);
if (cv.wait_for(lk, chrono::milliseconds(10), [this] { return canceled; }))
break;
}
cout << __PRETTY_FUNCTION__ << " done\n";
}
};
int main()
{
workers demo;
std::thread t1(&workers::thread1, ref(demo));
std::thread t2(&workers::thread2, ref(demo));
t1.join();
t2.join();
}
更新带boost的C++03版本现在也是。为了好玩,我添加了时间戳:
thread1:21 2014-Mar-26 00:01:40.074269 start
thread2:37 2014-Mar-26 00:01:40.074275 start
thread1:26 2014-Mar-26 00:01:42.074873 signaling cancel
thread2:47 2014-Mar-26 00:01:42.074991 done
thread1:32 2014-Mar-26 00:01:44.075062 done
用boost更新C++03版本现在也太难了。(我在输出中添加了时间戳作为奖励,如下所示)
thread1:21 2014-Mar-26 00:01:40.074269 start
thread2:37 2014-Mar-26 00:01:40.074275 start
thread1:26 2014-Mar-26 00:01:42.074873 signaling cancel
thread2:47 2014-Mar-26 00:01:42.074991 done
thread1:32 2014-Mar-26 00:01:44.075062 done