#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
using namespace std;
#define MAX_THREAD_COUNT 50
class A
{
public:
static void ExecDecrementX(void* thisObj, int *x)
{
cout << "DecrementX thread..." << endl;
A *obj = (A*)thisObj;
obj->DecrementX(x);
}
void DecrementX(int* x)
{
cout << "Thread Instantiated........" << endl;
for (; *x <= 1200; (*x)++)
{
cout << "DecrementX thread, X = " << *x << endl;
if (*x == 1100)
{
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, false, L"MyEvent1");
if (!hEvent) { return; }
ResetEvent(hEvent);
if (SetEvent(hEvent))
{
cout << "Got The signal - MyEvent 1......." << endl;
CloseHandle(hEvent);
}
}
}
cout << "End of the Thread ......" << endl;
}
};
int main()
{
int x = 1000;
A* obj1 = new A();
DWORD dwRet;
HANDLE Events_Handle[1];
HANDLE hEvent1 = CreateEvent(NULL, true, false, L"MyEvent1");
if (!hEvent1) return -1;
Events_Handle[0] = hEvent1;
void(*fPtr)(void*, int*) = A::ExecDecrementX;
boost::asio::io_service ioService;
boost::thread_group ThreadPool;
boost::asio::io_service::work work(ioService);
for (int threadcount = 0; threadcount < MAX_THREAD_COUNT; threadcount++)
{
ThreadPool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}
cout << "Main thread\n";
ioService.post(boost::bind(fPtr, obj1, &x));
while (1)
{
dwRet = WaitForMultipleObjects(1, Events_Handle, false, INFINITE);
cout << "dwRet = " << dwRet << endl;
if (dwRet == WAIT_OBJECT_0)
{
cout << "All events were signaled..." << endl;
ioService.stop();
ThreadPool.interrupt_all();
cout << "Remaining threads interrupted... X = " << x << endl;
CloseHandle(hEvent1);
break;
}
}
cout << "Main Thread: At the End X = " << x << endl;
return 0;
}
我是需求量的一次x达到1100,打断了所有的线程,但即使线程池的中断之后,我看到线程池的推移和保持印刷,直到结束。 你能帮我理解发生了什么,我该如何解决它?想一旦变量达到一定值时,终止线程池
感谢, JK
如果你想让你查看我录制的直播,重构这个答案[围绕18'45''标记](https://www.livecoding.tv/video/qihold-butchering-a-thread-fest-question/) 。特别是你可以看到我先用'boost :: condition_variable' /'mutex' /'unique_lock'组合代替了并处理了'thread_interrupted'异常(尽管我的最终代码并不包含任何这些代码),你仍然可能仍然想看?) – sehe