有没有办法只使用C++或Windows C++函数来创建线程池?我无法访问boost或任何库(我可以访问代码项目,但找不到任何非unix的东西),而且我发现很难找到实现线程池的方法。
我使用的是VS2010,它还不支持C++11线程,所以我有点卡住了!
发布于 2012-04-03 17:22:37
如果你的目标是Windows Vista或更高版本,你可以使用这个线程池:http://msdn.microsoft.com/en-us/library/windows/desktop/ms686980%28v=vs.85%29.aspx
该页面还提供了一个C++示例。
发布于 2012-04-03 21:14:29
这相当简单。您需要一些类:
带有“run”方法的任务类-池用户可以重写它来构建自己的任务。
一个生产者-消费者objectQueue,用于线程等待工作。如果你有std::deque,那就相当简单了。如果不是,则必须编写自己的队列类型。除了queue类之外,你还需要一些同步的东西,可能是一个CriticalSection/Mutex来保护队列,还有一个让线程等待的信号量。
threadPool类-包含P-C queue、submit(TaskClass aTask)方法和其他内容的类。
在threadPool中创建的一堆线程-使用CreateThread并将threadPool实例作为lpParam参数传递,以便线程可以再次强制转换它以访问threadPool。
线程在threadPool->objectQueue上等待工作,例如:
// header
class threadPool;
class task {
friend class threadPool;
private:
threadPool *myPool;
public:
virtual void run()=0;
};
class PCSqueue{
private:
CRITICAL_SECTION access;
deque<task*> *objectQueue;
HANDLE queueSema;
public:
PCSqueue();
void push(task *ref);
bool pop(task **ref,DWORD timeout);
};
class threadPool {
private:
int threadCount;
public:
PCSqueue *queue;
threadPool(int initThreads);
static DWORD _stdcall staticThreadRun(void *param){
threadPool *myPool=(threadPool *)param;
task *thisTask;
while (myPool->queue->pop(&thisTask,INFINITE)){
thisTask->run();
}
}
void submit(task *aTask);
};// cpp
PCSqueue::PCSqueue(){
objectQueue=new deque<task*>;
InitializeCriticalSection(&access);
queueSema=CreateSemaphore(NULL,0,MAXINT,NULL);
};
void PCSqueue::push(task *ref){
EnterCriticalSection(&access);
objectQueue->push_front(ref);
LeaveCriticalSection(&access);
ReleaseSemaphore(queueSema,1,NULL);
};
bool PCSqueue::pop(task **ref,DWORD timeout){
if (WAIT_OBJECT_0==WaitForSingleObject(queueSema,timeout)) {
EnterCriticalSection(&access);
*ref=objectQueue->back();
objectQueue->pop_back();
LeaveCriticalSection(&access);
return(true);
}
else
return(false);
};
threadPool::threadPool(int initThreads){
queue=new PCSqueue();
for(threadCount=0;threadCount!=initThreads;threadCount++){
CreateThread(NULL,0,staticThreadRun,this,0,0);
};
};
void threadPool::submit(task *aTask){
aTask->myPool=this;
queue->push(aTask);
};发布于 2012-04-03 17:11:17
有一个用于管理线程池的应用程序接口,这里有一个链接:http://msdn.microsoft.com/en-us/library/windows/desktop/ms686766(v=vs.85).aspx。不过,您可能希望找到一个包装它的库,因为它很复杂。
https://stackoverflow.com/questions/9989784
复制相似问题