Windows 中的互斥体与事件

发布于 2024-11-27 21:39:38 字数 238 浏览 2 评论 0原文

我很困惑,有什么区别

mutex = createMutex
waitForSingleObject
Release(mutex)

有人可以解释一下,如果我这样做并且

event = createEvent
waitForSingleObject
Release(event)

,我可以使用两个版本进行同步吗?预先感谢您的帮助

can somebody please explain what is the difference if I do

mutex = createMutex
waitForSingleObject
Release(mutex)

and

event = createEvent
waitForSingleObject
Release(event)

I'm so confused, can I use both versions for the synchronization? thanks in advance for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喜你已久 2024-12-04 21:39:38

您可以使用互斥锁来确保只有一个执行线程可以访问某些内容。例如,如果您想要更新可能被多个线程使用的列表,则可以使用互斥锁:

acquire mutex
update list
release mutex

使用互斥锁,一次只能有一个线程执行“更新列表”。

如果您希望多个线程在继续之前等待某些事情发生,则可以使用手动重置事件。例如,您启动了多个线程,但它们都已暂停,等待其他事件才能继续。一旦该事件发生,所有线程都可以开始运行。

主线程将如下所示:

create event, initial value false (not signaled)
start threads
do some other initialization
signal event

每个线程的代码将是:

do thread initialization
wait for event to be signaled
do thread processing

You use a mutex to ensure that only one thread of execution can be accessing something. For example, if you want to update a list that can potentially be used by multiple threads, you'd use a mutex:

acquire mutex
update list
release mutex

With a mutex, only one thread at a time can be executing the "update list".

You use a manual reset event if you want multiple threads to wait for something to happen before continuing. For example, you started multiple threads, but they're all paused waiting for some other event before they can continue. Once that event happens, all of the threads can start running.

The main thread would look like this:

create event, initial value false (not signaled)
start threads
do some other initialization
signal event

Each thread's code would be:

do thread initialization
wait for event to be signaled
do thread processing
坏尐絯 2024-12-04 21:39:38

是的,两者都可以用于同步,但方式不同。

Mutex 是一个互斥对象,一次只能由一个实例获取。它用于避免计算机代码片段同时使用公共资源(例如全局变量)

Event 是一个可以使用 SetEvent 函数显式设置为状态的对象。

Yes, both can be used for synchronization but in different ways.

Mutex is a mutual exclusion object and can be acquired only by a single instance at a time. It is used to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code

Event is an objet that can be explicitly set to a state by use of the SetEvent function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文