ros*_*b83 6 c++ windows queue events multithreading
我的程序设置如下:
有一个线程安全的队列类,一个线程在无限循环中将数据推送到它上面,第二个线程在坐在无限循环中时从其中弹出数据.我试图想办法使用Windows事件或其他机制来创建thread_1(下面),在无限循环中等待,并且只在队列深度大于或等于1时进行迭代.
class thread-safe_Queue
{
public:
push();
pop();
};
DWORD thread_1()
{
while(1)
{
// wait for thread-safe queue to have data on it
// pop data off
// process data
}
}
DWORD thread_2()
{
while(1)
{
// when data becomes available, push data onto thread-safe queue
}
}
Run Code Online (Sandbox Code Playgroud)
这个怎么样(我假设你熟悉事件机制)。
1.
thread_safe_Queue::push(something)
{
// lock the queue
...
// push object
// Signal the event
SetEvent(notification);
// unlock the queue
}
Run Code Online (Sandbox Code Playgroud)
2.
thread_safe_Queue::pop(something)
{
WaitForSingleObject(notification);
// lock the queue
...
// get object
// reset the event
if (queue is empty)
ResetEvent(notification);
// unlock the queue
}
Run Code Online (Sandbox Code Playgroud)
3. thread_1 只是尝试弹出对象并处理它。当有东西被推送时,事件被启用,因此pop可以成功调用。否则就会在里面等待pop。实际上,您可以使用其他同步对象(例如互斥体或临界区)来代替本例中的事件。
更新。外部事件:线程 1:
void thread_1()
{
while(1)
{
WaitForSingleObject(notification);
if (!pop(object)) // pop should return if there are any objects left in queue
SetEvent(notification);
}
}
Run Code Online (Sandbox Code Playgroud)
线程_2
void thread_2()
{
while(1)
{
// push the object and than signal event
ResetEvent(notification)
}
}
Run Code Online (Sandbox Code Playgroud)