Detailed explanation of Linux multi-thread synchronization mutex Mutex
Linux system is an operating system that supports concurrent execution of multi-tasks. It can run multiple processes at the same time, thereby improving system utilization and efficiency. However, if there are multiple threads in a process, and these threads need to share some data or resources, data inconsistency or resource competition may occur, leading to system errors or exceptions. In order to solve this problem, you need to use some synchronization mechanisms, such as semaphores, condition variables, mutexes, etc. Among them, the mutex is a relatively simple and effective synchronization mechanism. It allows a thread to lock shared data or resources when accessing them to prevent other threads from accessing them at the same time, thus ensuring thread safety. This article will explain in detail the method of synchronizing the mutex Mutex in Linux multi-threads, including the initialization, locking, unlocking and destruction of the mutex.
1. Initialization:
Under Linux, the thread's mutex data type is pthread_mutex_t. Before use, it must be initialized:
For statically allocated mutexes, you can set it to PTHREAD_MUTEX_INITIALIZER, or call pthread_mutex_init.
For a dynamically allocated mutex, after applying for memory (malloc), it is initialized through pthread_mutex_init, and pthread_mutex_destroy needs to be called before releasing the memory (free).
prototype:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
head File:
Return value: Returns 0 if successful, returns error number if error occurs.
Note: If you use the default attributes to initialize the mutex, just set attr to NULL. Other values will be explained later.
2. Mutually exclusive operation:
To access shared resources, you need to lock the mutex. If the mutex is already locked, the calling thread will block until the mutex is unlocked. After completing the access to the shared resources, you need to Unlock the mutex.
Let’s talk about the locking function:
head File:
prototype:
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
Return value: Returns 0 if successful, returns error number if error occurs.
Description: Let’s talk specifically about the trylock function. This function is a non-blocking calling mode. That is to say, if the mutex is not locked, the trylock function will lock the mutex and gain access to the shared resources; If the mutex is locked, the trylock function will not block waiting and directly return EBUSY, indicating that the shared resource is busy.
Let’s talk about the solution function:
head File:
Prototype: int pthread_mutex_unlock(pthread_mutex_t *mutex);
Return value: Returns 0 if successful, returns error number if error occurs.
\3. Deadlock:
Deadlock mainly occurs when there are multiple dependent locks, and it occurs when one thread tries to lock the mutex in the opposite order as another thread. How to avoid deadlock is something that should be paid special attention to when using mutexes. .
Generally speaking, there are several unwritten basic principles:
Be sure to obtain the lock before operating on shared resources.
Be sure to release the lock after completing the operation.
If there are multiple locks, if the acquisition sequence is ABC, the release sequence should also be ABC.
The thread should release the lock it acquired when it returns an error.
Example:
#include #include #include #include #include pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int lock_var; time_t end_time; int sum; void pthread1(void *arg); void pthread2(void *arg); void pthread3(void *arg); int main(int argc, char *argv[]) { pthread_t id1,id2,id3; pthread_t mon_th_id; int ret; sum=10; end_time = time(NULL) 10; pthread_mutex_init(&mutex,NULL); ret=pthread_create(&id1,NULL,(void *)pthread1, NULL); if(ret!=0) perror("pthread cread1"); ret=pthread_create(&id2,NULL,(void *)pthread2, NULL); if(ret!=0) perror("pthread cread2"); ret=pthread_create(&id3,NULL,(void *)pthread3, NULL); if(ret!=0) perror("pthread cread3"); pthread_join(id1,NULL); pthread_join(id2,NULL); pthread_join(id3,NULL); exit(0); } void pthread1(void *arg) { int i; while(time(NULL) if(pthread_mutex_lock(&mutex)!=0) //lock { perror("pthread_mutex_lock"); } else printf("pthread1:pthread1 lock the variablen"); for(i=0;iif(pthread_mutex_unlock(&mutex)!=0) //unlock { perror("pthread_mutex_unlock"); } else printf("pthread1:pthread1 unlock the variablen"); sleep(1); } } void pthread2(void *arg) { int nolock=0; int ret; while(time(NULL) if(ret==EBUSY) printf("pthread2:the variable is locked by pthread1n"); else{ if(ret!=0) { perror("pthread_mutex_trylock"); exit(1); } else printf("pthread2:pthread2 got lock.The variable is %dn",lock_var); if(pthread_mutex_unlock(&mutex)!=0)//unlock { perror("pthread_mutex_unlock"); } else printf("pthread2:pthread2 unlock the variablen"); } sleep(1); } } void pthread3(void *arg) {/* int nolock=0; int ret; while(time(NULL) if(ret==EBUSY) printf("pthread3:the variable is locked by pthread1 or 2n"); else { if(ret!=0) { perror("pthread_mutex_trylock"); exit(1); } else printf("pthread3:pthread3 got lock.The variable is %dn",lock_var); if(pthread_mutex_unlock(&mutex)!=0) { perror("pthread_mutex_unlock"); } else printf("pthread3:pthread2 unlock the variablen"); } sleep(3); }*/ }
This article explains in detail the method of synchronizing the mutex Mutex in Linux multi-threads, including the initialization, locking, unlocking and destruction of the mutex. By understanding and mastering this knowledge, we can better use mutexes to achieve synchronization between multiple threads and improve the stability and efficiency of the system.
The above is the detailed content of Detailed explanation of Linux multi-thread synchronization mutex Mutex. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.
