1024programmer Blog The difference between lock_guard and unique_lock in c++11_The difference between lock_guard and unique_lock_GoKu~’s Blog

The difference between lock_guard and unique_lock in c++11_The difference between lock_guard and unique_lock_GoKu~’s Blog

Analysis of the use of lock_guard and unique_lock in c++11

Lock
Locks are used to prevent data races when multiple threads access the same resource, ensuring Consistent access to data.

Multithreading is originally to improve efficiency and response speed, but the use of locks limits the parallel execution of multithreading, which will reduce efficiency, but in order to ensure correct data, locks have to be used, and they are entangled like this.

As a c++ developer who prioritizes efficiency, many people talk about locking color.

Although there are many lock-free technologies applied to the project, it is still necessary to have a basic understanding of the lock technology. This article mainly discusses two kinds of locks in c++11: lock_guard and unique_lock.

Combined with locks to synchronize the use of condition variables between threads, please refer to the condition variable condition variable.

lock_guard
lock_guard is a mutex wrapper that provides a convenient RAII (Resource acquisition is initialization) style mechanism to own a mutex for the duration of a scoped block.

When a lock_guard object is created, it attempts to take ownership of the mutex provided to it. When the control flow leaves the scope of the lock_guard object, the lock_guard destroys and releases the mutex.

Its characteristics are as follows:

Creation is locked, and the scope is automatically destructed and unlocked, no need to manually unlock
Cannot be unlocked halfway, you must wait for the scope to end before unlocking
Cannot be copied
The sample code is as follows:

#include
#include
#include

int g_i = 0;
std::mutex g_i_mutex; // protects g_i
>
void safe_increment()
{

const std::lock_guard lock(g_i_mutex);
++g_i;

std::cout << std::this_thread: :get_id() << ": " << g_i << '\n';

// g_i_mutex is automatically released when lock
// goes out of scope
}

int main()
{

std::cout << "main: " << g_i << '\n';

std::thread t1(safe_increment);
std: :thread t2(safe_increment);

t1.join();
t2.join();

std::cout << "main: " << g_i << ' \n';
}

Output:

main: 0
140641306900224: 1
140641298507520: 2
main: 2

unique_lock
unique_lock is a generic mutex lock wrapper that allows delayed locking , time-limited deep locking, recursive locking, transfer of lock ownership, and use with condition variables.

Simply speaking, unique_lock is an upgraded and enhanced version of lock_guard. It has all the functions of lock_guard and has many other methods. It is more flexible and convenient to use, and can meet more complex locking needs.

The features are as follows:

You can not lock it when you create it (by specifying the second parameter as std::defer_lock), and lock it when you need it
You can lock and unlock it at any time
The scope rules are the same as lock_grard, and it will be released automatically when it is destructed Lock
cannot be copied, but can be moved
The condition variable requires a lock of this type as a parameter (unique_lock must be used in this case)
Example code:

#include
#include
#include

struct Box {

explicit Box(int ​​num) : num_things{num} {}

int num_things;
std::mutex m;
};

void transfer(Box &from, Box &to, int num)
{

// don’t actually take the locks yet
std::unique_lock lock1(from.m, std::defer_lock);
std: :unique_lock lock2(to.m, std::defer_lock);

// lock both unique_locks without deadlock
std::lock(lock1, lock2);

from.num_things -= num;
to.num_things += num;

// ‘from.m’ and ‘to.m’ mutexes unlocked in ‘unique_lock’ dtors
}

int main()
{

Box acc1(100);
Box acc2(50);

std::thread t1(transfer, std::ref(acc1), std:: ref(acc2), 10);
std::thread t2(transfer, std::ref(acc2), std::ref(acc1), 5);

t1.join();
t2.join();
}

Summary
All things that lock_guard can do can be done with unique_lock, The opposite is not true.

So when to use lock_guard? Very simple,

When you need to use locks, first consider using lock_guard
It is simple, clear and easy to read. If it’s completely ok to use, don’t consider anything else.

If the reality doesn’t allow it, let unique_lock be the one with strength!
———————————————————
Copyright statement: This article is an original article of CSDN blogger “guotianqing”, following the CC 4.0 BY-SA copyright agreement, please attach The link to the source of the original text and this statement.
Original link: https://blog.csdn.net/guotianqing/article/details/104002449

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/the-difference-between-lock_guard-and-unique_lock-in-c11_the-difference-between-lock_guard-and-unique_lock_gokus-blog/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索