search
HomeBackend DevelopmentPHP TutorialLinux--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

Linux--Thread synchronization and mutual exclusion

Result:

Linux--Thread synchronization and mutual exclusion

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.

Linux--Thread synchronization and mutual exclusion

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)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool