是否有一组 Win32 API 函数来管理同步队列? [英] Is there a set of Win32 API functions to manage synchronized queues?
问题描述
我有一个包含多个工作线程的程序和一个接收作业的主线程.在主线程中,我想将作业排队到一个同步队列中,并让所有工作线程都坐在那里等待队列.当队列中有东西时,我希望工作人员从队列中提取作业,而其余的工作则坐在那里等待另一份工作.
I have a program with several worker threads, and a main thread that receives jobs. In the main thread I want to queue the jobs onto a synchronized queue, and have the worker threads sitting there all waiting on the queue. When there's something in the queue I want the worker to pull the job from the queue, while the remaining work sits there waiting for another job.
我找到了 CreateMsgQueue (http://msdn.microsoft.com/en-us/library/ms885180.aspx) 但是这似乎只适用于 Windows CE.
I found CreateMsgQueue (http://msdn.microsoft.com/en-us/library/ms885180.aspx) however this appears to only exist for Windows CE.
我知道我可以自己写这个,但是如果某些东西已经存在,我不使用它就是个傻瓜.
I know I could write this myself, however if something already existed I'd be a fool not to use it.
我正在使用 Visual Studio 2005 用 C++ 进行开发.
I am developing in c++ using Visual Studio 2005.
感谢收到任何建议.
谢谢丰富的
推荐答案
Windows 并没有完全提供您想要的.它提供的是线程池 -- 有了这些,您不仅不必自己创建队列,而且也不必创建或(直接)管理线程.
Windows doesn't provide exactly what you want. What it does provide is thread pools -- with these, you not only don't have to create the queue yourself, but you don't have to create or (directly) manage the threads either.
当然,同步队列也确实存在,只是不是 Windows 的一部分.我写的一个看起来像这样:
Of course, synchronized queues do exist too, just not as part of Windows. One I wrote looks like this:
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
#include <windows.h>
template<class T, unsigned max = 256>
class queue {
HANDLE space_avail; // at least one slot empty
HANDLE data_avail; // at least one slot full
CRITICAL_SECTION mutex; // protect buffer, in_pos, out_pos
T buffer[max];
long in_pos, out_pos;
public:
queue() : in_pos(0), out_pos(0) {
space_avail = CreateSemaphore(NULL, max, max, NULL);
data_avail = CreateSemaphore(NULL, 0, max, NULL);
InitializeCriticalSection(&mutex);
}
void push(T data) {
WaitForSingleObject(space_avail, INFINITE);
EnterCriticalSection(&mutex);
buffer[in_pos] = data;
in_pos = (in_pos + 1) % max;
LeaveCriticalSection(&mutex);
ReleaseSemaphore(data_avail, 1, NULL);
}
T pop() {
WaitForSingleObject(data_avail,INFINITE);
EnterCriticalSection(&mutex);
T retval = buffer[out_pos];
out_pos = (out_pos + 1) % max;
LeaveCriticalSection(&mutex);
ReleaseSemaphore(space_avail, 1, NULL);
return retval;
}
~queue() {
DeleteCriticalSection(&mutex);
CloseHandle(data_avail);
CloseHandle(space_avail);
}
};
#endif
这篇关于是否有一组 Win32 API 函数来管理同步队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!