Linux--Thread synchronization and mutual exclusion
1. Mutex mutex
Synchronization: access to resources in an orderly manner. Mutual exclusion: only one is executing at any time; but for multi-threaded programs, the problem of access conflicts is very common. The solution is to introduce a mutex (Mutex, MutualExclusive Lock), and obtain the lock. The thread can complete the "read-modify-write" operation and then release the lock to other threads. Threads that have not obtained the lock can only wait but cannot access the shared data. In this way, the three-step operation of "read-modify-write" forms an atomic operation. Either execute them all or neither, they will not be interrupted in the middle of execution, and this operation will not be done in parallel on other processors.
Mutex locks are represented by variables of type pthread_mutex_t. Initialized with pthread_mutex_init and destroyed with hread_destroy(). Returns 0 on success and an error number on failure. . If the Mutex variable is statically allocated (global variable or static variable), it can also be initialized with the macro definition PTHREAD_MUTEX_INITIALIZER, which is equivalent to initializing with pthread_mutex_init and the attr parameter is NULL
A thread can call pthread_mutex_lock to obtain the Mutex. If at this time another thread If the thread has called pthread_mutex_lock to obtain the Mutex, the current thread needs to wait until another thread calls pthread_mutex_unlock to release the Mutex, and the current thread is awakened before it can obtain the Mutex and continue execution. This means that if a thread locks the mutex but does not unlock it, and another thread wants to obtain the mutex, it must hang up and wait until the locked thread unlocks the mutex and releases the mutex, and then the thread is awakened and can obtain the mutex.
If a thread wants to obtain the lock but does not want to hang and wait, it can call pthread_mutex_trylock. If the Mutex has been acquired by another thread, this function will fail and return EBUSY without causing the thread to hang and wait.
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<pthread.h> 4 static int g_count=0; 5 void * addWrite(void * arg) 6 { 7 int count=0; 8 int value=0; 9 while(count++ <5000) 10 { 11 value=g_count; 12 printf("g_count is %d\n",g_count); 13 g_count=value+1; 14 } 15 } 16 int main() 17 { 18 pthread_t id1; 19 pthread_t id2; 20 int ret=pthread_create(&id1,NULL,addWrite,NULL); 21 int res=pthread_create(&id2,NULL,addWrite,NULL); 22 pthread_join(id1,NULL); 23 pthread_join(id2,NULL);
We create two threads, each increasing g_count 5000 times. Under normal circumstances, the final counter should be equal to 10000, but in fact the result is different every time the program is run. Sometimes the count reaches more than 5000. Sometimes the count reaches more than 6,000, but after adding the lock (on) the fifth line, add pthread_mutex_init, as shown below
Result:
After adding the lock, 10000 is output.
2. Implementation principle of lock and unlock
In order to realize the mutex lock operation, most architectures provide the swap or exchange instruction. The instruction is The function is to exchange data between the register and the memory unit. Since there is only one instruction, atomicity is guaranteed. Even on a multi-processor platform, the bus cycles for accessing memory are sequential. The exchange instruction on one processor is executed on another processor. The swap instruction can only wait for bus cycles. This is shown in the pseudocode below. The lock release operation in unlock is also implemented with only one instruction to ensure its atomicity.
3. Deadlock
・Generally, if the same thread calls lock twice, during the second call, because the lock has already been occupied, The thread will hang up and wait for other threads to release the lock. However, the lock is occupied by itself. The thread is suspended without a chance to release the lock, so it will be in a suspended waiting state forever. This is called deadlock. ). Another typical deadlock situation is this: Thread A acquires lock 1, and thread B acquires lock 2. At this time, thread A calls lock to try to acquire lock 2. As a result, it needs to hang and wait for thread B to release lock 2, and this At this time, thread B also called lock to try to obtain lock 1. As a result, it needed to wait for thread A to release lock 1, so both threads A and B were in a suspended state forever.
Conditions for deadlock formation
①. Mutual exclusion condition: A resource can only be used by one thread at a time.
②. Request and retention conditions: When a process is blocked due to requesting resources, it will retain the obtained resources.
③. Non-deprivation conditions: The resources that have been obtained by the process cannot be forcibly deprived before they are used up.
④Cyclic waiting conditions: A head-to-tail cyclic waiting resource relationship is formed between several processes.
If more threads and more locks are involved, it is more likely to cause Deadlock problem. When writing a program, you should try to avoid acquiring multiple locks at the same time. If it is necessary to do so, there is a principle: if all threads need multiple locks, they must follow the same order (the most common is the address order of the Mutex variable) If the lock is obtained, deadlock will not occur. For example, if lock 1, lock 2, and lock 3 are used in a program, and the addresses of their corresponding Mutex variables are lock 1
The above is the content of Linux-thread synchronization and mutual exclusion. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

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



How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to back up VS Code configurations and extensions? Manually backup the settings file: Copy the key JSON files (settings.json, keybindings.json, extensions.json) to a safe location. Take advantage of VS Code synchronization: enable synchronization with your GitHub account to automatically back up all relevant settings and extensions. Use third-party tools: Back up configurations with reliable tools and provide richer features such as version control and incremental backups.
