linux - 多线程编程中的mutex
PHP中文网
PHP中文网 2017-04-17 16:28:49
0
3
850
#include <mutex>

int a;
char c;
std::mutex t;

int main()
{
    std::lock_guard<std::mutex> zz(t);
    a = 2;
    c = '1';
    return 0;
}

如上面这小段代码,请问c++11中的mutex,是不是只要mutex被锁住了,就是默认对所有的共享数据加上了锁?

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
巴扎黑

The scope of the lock depends on the scope of your lock, so in your test program, the main scope is locked.
Of course, your sample program itself is meaningless because it is not used in multi-threading. Assume it is multi-threaded. At this time, other threads need to wait for your mutex lock to be released when trying to lock the mutex, which means that only one thread can access variables a and c at a certain time.

PHPzhong

After locking, the mutex lock is held unless the current thread releases it. When the current thread acquires the lock, it has already completed executing this line of code and entered the next line of execution, so it is qualified to release the mutex lock. Other threads waiting for the lock will sleep in this line of code before the lock is released, until they are awakened from the waiting queue by the operating system.

Mutex lock controls resource access. Entering the critical section requires obtaining a lock. At this time, the thread has the power to consume resources, that is, to modify the shared data. Exiting the critical section requires releasing the lock and releasing the lock to other threads to continue execution.

巴扎黑

To put it simply, no. Mutex is a kind of lock. It only ensures that one thread can lock it at the same time, but how to control the global variables is implemented by your own code. That is to say, it is an agreement that if another thread does not try to lock the Mutex first, but directly modifies those global variables, it will not be blocked.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template