效仿线程池的问题
我效仿的线程池,和平常的线程池不大一样。
想实现功能。开始创建n个线程。在线程函数中,判断是否有可用资源,退出。但只要有一个线程获取的资源,另外n-1个线程挂起。在线程处理资源时,如果资源过大,拆分,唤醒n-1个线程来处理。故我写了一个管理线程类。一个map保存挂起的线程,一个map保存工作线程。但有个问题,在线程内通过GetCurrentThread获取的handle,经常会获取失败。请问你们在线程池中,是保存什么来操作线程的呢?
[解决办法]
启动线程时,就可以得到handle和线程id了
[解决办法]
安全关闭线程,参考这个帖子
http://topic.csdn.net/u/20111116/16/49927aac-7def-4f5e-8f12-713782750371.html
[解决办法]
#include "stdafx.h"#include <Windows.h>#include <iostream>#include <DbgHelp.h>#include <map>using namespace std;#include <process.h>map<int,int> thread_map;unsigned int __stdcall __thread(void* para){ while(1) { int id =GetCurrentThreadId(); SuspendThread((HANDLE)thread_map[id]); } _endthread(); return 0;}#pragma comment( lib, "Dbghelp.lib" )LONG __stdcall UnhandledExceptionFilterCall( __in struct _EXCEPTION_POINTERS *ExceptionInfo );int _tmain(int argc, _TCHAR* argv[]){ //SetUnhandledExceptionFilter( UnhandledExceptionFilterCall ); unsigned int threadid = 0; int handle = _beginthreadex(NULL,0,__thread, 0, 0 ,&threadid); thread_map[threadid] =handle; while(1) { Sleep(1000); switch(getchar()) { case 'r': { ResumeThread((HANDLE)handle); } break; case 's': { SuspendThread((HANDLE)handle); } break; } } system("pause"); return 0;}