且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std :: thread和events

更新时间:2023-11-11 22:38:40

答案实际上是在对该问题的评论中写的Zeee-M和我。



这是你可以使用的:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682655%28v=vs .85%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686211(v = vs.85).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/windows/desktop/ms685081(V = vs.85)的.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032%28v=vs.85%29.aspx [ ^ ]。



自动重置事件提供了一个额外的功能,无法通过手动重置模拟:当设置事件对象时,它可以只允许一个对象通过。如果队列中有另一个对象,它将进入等待状态,直到再次调用 SetEvent







使用任何条件变量都无法解决此问题,并且在使用级别上没有其他任何内容。它在OS的内核中实现,其中代码可以访问抢占机制和线程的等待状态以及唤醒它们的机制。所有这些都隐藏在系统中,只允许通过等待对象间接使用。



当线程处于等待状态时,它被关闭,从不计划返回执行(它被排除在抢占线程集之外)直到被唤醒。超时或事件对象的设置是两种唤醒方式。这样的线程在被唤醒之前不会花费任何CPUI时间。这不能直接在用户代码的级别上完成。







对不起,我回答了Windows API,没注意你提到 std :: thread 。使用 std :: thread 表示在C ++ 11中引入的标准API。但所有的想法都是一样的;用法非常相似。



这里解释了条件变量的使用:http://www.cplusplus.com/reference/condition_variable/condition_variable [ ^ ]。



如果这是你使用的,如果你还有一些问题,你需要创建一个代码示例并解释您对该示例的问题。



-SA
The answer is actually in the comment to the question written by Zeee-M and myself.

This is what you can use:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682655%28v=vs.85%29.aspx[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686211(v=vs.85).aspx[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms685081(v=vs.85).aspx[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032%28v=vs.85%29.aspx[^].

Auto-reset event provides an additional feature which cannot be simulated with manual reset: when the event object is set, it can allow exactly one object to pass. If another object is in the queue, it will get to the wait state until another call to SetEvent.



This problem cannot be solved using any conditional variable, and nothing else on the use level. It is implemented in the kernel of the OS, where the code has access to the preemption mechanism and the wait state of thread and the mechanism of waking them up. All this is hidden in the system, to allow only the indirect use through wait objects.

When the thread is put in the wait state, it is switched off and never scheduled back again to execution (it is excluded from the set of preempting threads) until is waken up. The timeout or the setting of an event object is two ways of waking up. Such thread is not spending any CPUI time until it is waken up. This cannot be done directly on the level of the user code.



Sorry, I answered in terms of Windows API, did not pay attention that you mentioned std::thread. The use of std::thread means the standard API introduced in C++11. But all the ideas are the same; and the usage is very similar.

The use of condition variable is explained here: http://www.cplusplus.com/reference/condition_variable/condition_variable[^].

If this is what you used and if you still had some problems, you would need to create a code sample and explain your problem on that sample.

—SA