为什么使用互斥体而不是布尔变量进行线程同步? [英] Why to use mutex instead of boolean variable for thread synchronization?

查看:51
本文介绍了为什么使用互斥体而不是布尔变量进行线程同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 C 中的多线程编程.

I'm trying to understand the multithreading programming in C.

我怀疑既然我们使用 MUTEXES 进行线程同步,为什么我们不能使用布尔变量来阻塞要执行的代码的关键区域.

I have doubt that as we uses MUTEXES for thread synchronization, why we can't use Boolean variable to block the critical area of code to be executed.

布尔变量静音的特长是什么?

What is specialty of mutes over Boolean variable?

PS:其实这个问题是在面试的时候问的.所以请分享您对此的了解.

PS: Actually this question was asked in an interview. So please share your knowledge about this.

推荐答案

问题是两个线程可以同时将布尔值视为可用,然后都认为继续是安全的.

The problem is that two threads could both see the Boolean value as available at the same time, and both would then assume that it's safe to continue.

例如,假设您有以下代码:

For example, say you have this code:

bool myLock = false;  // visible to all threads

void someFunction()
{
    if (!myLock)
    {
        myLock = true;
        // do whatever
        // and then release the lock
        mylock = false;
    }
}

现在,假设有两个线程正在执行.线程 A 读取 myLock 并看到它是 false,所以它继续执行下一条指令.同时,线程 B 读取 myLock 并看到它是 false,因为线程 A 尚未将其设置为 true.所以线程 B 继续前进并获取锁.此时,两个线程都在执行应该受互斥锁保护的代码.

Now, imagine that two threads are executing. Thread A reads myLock and sees that it's false, so it goes on to the next instruction. At the same time, Thread B reads myLock and sees that it's false, because Thread A hasn't yet set it to true. So Thread B goes right ahead and takes the lock, too. At this point, both threads are executing the code that's supposed to be protected by a mutual exclusion lock.

情况变得更糟,因为线程 A 完成了它正在执行的操作并将 mylock 设置回 false 而线程 B 仍在执行.因此,即使线程 B 仍在那里,另一个线程也可以出现并获取锁.

It gets worse because Thread A finishes what it's doing and sets mylock back to false while Thread B is still executing. So another thread can come along and take the lock even though Thread B is still in there.

互斥锁保证原子性.也就是说,它保证检查和更新一次只能由一个线程完成.所以如果你用互斥锁替换布尔值,你有:

A mutex guarantees atomicity. That is, it guarantees that the check-and-update can only be done by a single thread at a time. So if you replace the boolean with a mutex, you have:

if (mutex.Acquire())
{
    // do stuff
    // then release the lock
    mutex.Release();
}

两个线程不可能同时获取互斥锁.

There's no chance that two threads can acquire the mutex simultaneously.

这篇关于为什么使用互斥体而不是布尔变量进行线程同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆