答案 0 :(得分:22)
互斥意味着在任何给定的时间点,只有一个线程应该能够访问共享资源。这避免了获取资源的线程之间的竞争条件。监视器和锁定提供了这样做的功能。
同步表示您将多个线程的访问权限同步/排序到共享资源。
考虑一下这个例子:
如果你有两个主题,Thread 1
& Thread 2
。
Thread 1
和Thread 2
并行执行,但在Thread 1
可以执行之前,在其序列中声明A
,Thread 2
必须执行语句{{} 1}}在它的序列中。你需要的是同步。信号量提供了这一点。您在B
中的语句A
之前等待semapohore等待,并在Thread 1
中的语句B
之后发布到信号量。
这可确保您需要的同步。
答案 1 :(得分:0)
理解差异的最好方法是借助一个例子.Below是通过信号量解决经典生产者消费者问题的程序。为了提供互斥,我们通常使用二进制信号量或互斥量并提供我们使用的同步计算信号量。
BufferSize = 3;
semaphore mutex = 1; // used for mutual exclusion
semaphore empty = BufferSize; // used for synchronization
semaphore full = 0; // used for synchronization
Producer()
{
int widget;
while (TRUE) { // loop forever
make_new(widget); // create a new widget to put in the buffer
down(&empty); // decrement the empty semaphore
down(&mutex); // enter critical section
put_item(widget); // put widget in buffer
up(&mutex); // leave critical section
up(&full); // increment the full semaphore
}
}
Consumer()
{
int widget;
while (TRUE) { // loop forever
down(&full); // decrement the full semaphore
down(&mutex); // enter critical section
remove_item(widget); // take a widget from the buffer
up(&mutex); // leave critical section
consume_item(widget); // consume the item
}
}
在上面的代码中,互斥变量提供互斥(只允许一个线程访问临界区),而完全变量和空变量用于同步(以便在各种线程之间实现共享资源的访问)。