线程同步之mutex和event区别

时间:2022-12-22 05:59:37

之前只是用过 关键段来对同进程不同线程进行互斥,防止对同一份资源或代码段的竞争;

mutex可以理解为不同进程或者同一进程内防止对同一份资源的竞争;

event更多的是同步,当然也是不同进程或者同一进程,用于事件的同步,要先做A再做B,这时候就可以用Event来通知;

嗯,我立即的可能还是有问题的,还是收录些大牛的评论吧:

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 forevent to be signaled
do thread processing