Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Several types of locks in C++ threads

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "there are several kinds of locks in C++ thread". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought slowly and deeply. Let's study and learn how many kinds of locks are there in the C++ thread.

Several kinds of locks in C++ thread

There are five main types of locks in multithreading: mutex lock, conditional lock, spin lock, read-write lock and recursive lock. Generally speaking, the resulting function is inversely proportional to performance. And we generally do not use recursive locks (C++ provides std::recursive_mutex), so we will not introduce them here.

Mutex lock

Mutex A semaphore used by multiple threads to control mutually exclusive access to shared resources between them. That is to say, in order to prevent multiple threads from operating on a shared resource at the same time, such as a global variable, any thread should use the initial lock to mutually exclusive access to avoid confusion of multiple threads accessing at the same time.

At some point, only one thread can acquire the mutex, and no other thread can acquire the mutex until the mutex is released, waiting in a waiting queue in a blocked state.

Header file: # include

Type: std::std::mutex, std::lock_guard

Usage: in C++, create a mutex by constructing an instance of std::mutex, call the member function lock () to lock the shared resource, and call unlock () to unlock it. However, generally do not use this solution, more often use the C++ standard library of the std::lock_guard class template, the implementation of a mutex wrapper, providing a convenient RAII-style mechanism in the scope block.

Sample code:

# include # include / / C++ 11 thread library is a cross-platform # include / / C++ mutex # include # include int g_num = 0 cout STD include / / C++ mutex (int a) {cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 237

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report