我有两个测试来中断 boost::thread。一个有效,另一个无效。谁能告诉我为什么?
在职的:
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <unistd.h>
using namespace std;
void Run(void)
{
try
{
cout << "Run()\n";
for ( int i = 0; i < 1000; i++ )
{
cout << "Thread: " << i << endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
} catch (...)
{
cout << "INTERRUPTED!\n";
}
cout << "Thread returning.\n";
};
int main()
{
boost::thread my_thread(Run);
sleep(1);
cout << "Main() sleeping\n";
sleep(1);
cout << "Main() interrupting the thread\n";
my_thread.interrupt();
sleep(1);
cout << "Main() bye!!\n";
}
像这样编译:g++ test1.cpp -lboost_thread -lboost_system; ./a.out
输出是:
Run()
Thread: 0
Thread: 1
Main() sleeping
Thread: 2
Thread: 3
Main() interrupting the thread
INTERRUPTED!
Thread returning.
Main() bye!!
破碎的:
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <unistd.h>
using namespace std;
class CThread
{
public:
void Interrupt() { cout << "calling interrupt\n"; ThreadHandle.interrupt(); }
protected:
static unsigned int Init(void * process);
virtual int Run(void) =0;
void StartThread(void);
boost::thread ThreadHandle;
};
unsigned int CThread::Init(void * process)
{
cout << "Init()\n";
return ((CThread *)process)->Run();
}
void CThread::StartThread(void)
{
boost::thread ThreadHandle(CThread::Init, this);
}
class my_thread_class : public CThread
{
public:
my_thread_class();
int Run(void)
{
cout << "Run(), thread running\n";
for ( int i = 0; i < 1000; i++ )
{
cout << "Thread: " << i << endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
}
cout << "Thread returning.\n";
return 0;
};
};
my_thread_class::my_thread_class()
{
StartThread();
}
int main()
{
my_thread_class my_thread;
sleep(1);
cout << "Main() sleeping\n";
sleep(2);
cout << "Main() interrupting the thread\n";
my_thread.Interrupt();
sleep(5);
cout << "Main() bye!!\n";
}
相同的编译,损坏的输出是:
Init()
Run(), thread running
Thread: 0
Thread: 1
Main() sleeping
Thread: 2
Thread: 3
Main() interrupting the thread
calling interrupt
Thread: 4
Thread: 5
Main() bye!!
所以它似乎并没有打断我的破案。