[Linux programming] Thread Synchronization

Source: Internet
Author: User

Thread creation: [Linux programming] Thread Programming

When multiple control threads share the same data, ensure that each thread sees consistent data. When a thread modifies a data variable, other threads may see inconsistent data when reading the variable value.In the processing structure where the variable modification time is more than one storage access, when the two cycles of memory reading or writing cross, potential data inconsistency will occur.. To solve this data inconsistency problem, the thread uses the locking mechanism to ensure data consistency. If data reading or writing is an atomic operation, there is no data competition or data inconsistency problem.

1. mutex lock (pthread_mutex_t)

The mutex lock ensures that only one thread can access data at a time. Any other attempt to obtain the mutex lock that has been locked will be blocked until the current thread releases the mutex lock. If multiple threads are blocked, after the mutex lock is released, it will wake up all blocked threads and takeFirst come first served policyTo assign the right to use the mutex lock.

Mutex lock Initialization:

    • Use the constant pthread_mutex_initializer to initialize the mutex of static allocation;
    • For the dynamically assigned mutex, call the pthread_mutex_init () function to initialize the object. Call the pthread_mutex_destroy () function to initialize the object. Note that these two functions are paired in a way similar to malloc/free.

Use of mutex lock:

    • The pthread_mutex_lock () function is used to lock mutex locks. If the mutex lock is locked, the current thread will be blocked;
    • If the system thread is blocked when the system thread cannot obtain the mutex lock, call the pthread_mutex_trylock () function to try to lock the mutex lock. If the mutex is obtained successfully, the system locks the mutex and returns 0. If the result fails, the system returns non-0 and sets the error code to ebusy.
    • The pthread_mutex_unlock () function is used to unlock the mutex lock.

If a thread tries to lock the same mutex twice, it will be in a deadlock state. When using the lock mechanism, the lock sequence must be designed in advance to avoid deadlocks.


 1 # Include <unistd. h> 2 # Include <pthread. h> 3 # Include <stdio. h> 4   5 Pthread_mutex_t Lock = Pthread_mutex_initializer;  6  7   Void * Start_routine ( Void * Arg)  8   {  9       Int  Res;  10       Int Times = 0  ;  11 Pthread_t thread_id = Pthread_self ();  12  13       While ( 1  ){  14 Res = pthread_mutex_trylock (& Lock  );  15           If (Res! = 0  )  16   {  17 ++ Times;  18 Printf ( "  Now the mutex lock is using!  "  );  19 Printf ( "  And thread ID 0x % x is trying % d times! \ N  "  ,  20 (Unsigned Int  ) Thread_id, times );  21 Sleep ( 2 );  22               Continue  ;  23   }  24   25 Printf ( "  OK, 0x % x get mutex \ n  " , (Unsigned Int  ) Thread_id );  26 Times = 0  ; 27 Sleep ( 10  );  28 Pthread_mutex_unlock (& Lock  );  29           30           If (Times = 0  )  31               Break  ;  32   } 33   34 Pthread_exit (( Void * ) Thread_id );  35   }  36   37   Int  Main ()  38   {  39   Pthread_t id0, id1;  40       Int  Res; 41   42 Res = pthread_create (& Id0, null, start_routine, null );  43       If (RES < 0  )  44   {  45 Perror ( "  Pthread_create error!  "  );  46          Return (- 1  );  47   }  48       49 Res = pthread_create (& Id1, null, start_routine, null );  50       If (RES < 0  )  51   {  52 Perror ("  Thread_create error!  "  );  53           Return (- 1  );  54   }  55   56 Sleep ( 20  );  57 Printf ( " Mutexdemo is over! \ N  "  );  58   59       Return   0  ;  60   61 }

View code

Running result:

In the multi-threaded design process, the locking sequence and the lock granularity must be considered, that is, the data processing process in the locking process. If the granularity is too coarse, many threads will block and wait for the same lock, resulting in minimal improvement in concurrency performance. If the lock granularity is too small, too much lock overhead will affect the system performance, andCodeIt will become more complex. When designing a lock, you need to find a good balance between Code complexity and optimization performance when the lock requirements are met.

2. read/write lock (pthread_rwlock_t)

Unlike a mutex lock, only one thread can lock it at a time. The read/write locks are available in three states: the locking status in Read mode, the locking status in write mode, and the non-locking status. Only one thread can occupy the read/write lock in the write mode at a time, but multiple threads can simultaneously occupy the read/write lock in the Read mode. Therefore,Read/write locks can also be called shared-exclusive locks. When a read/write lock is locked in Read mode, it is locked in shared mode. When it is locked in write mode, it is locked in exclusive mode..

When a read/write lock is locked in Read mode, if another thread attempts to lock the lock in write mode, the subsequent read Mode Lock requests will be blocked.. If multiple threads lock in write mode, the processing method is the same as that of mutex lock.

The initialization of the read/write locks is completed using pthread_rwlock_init (). The pthead_rwlock_destroy () function must be called to initialize the read/write locks before the underlying memory is released.

Use of read/write locks:

    • Lock in Read mode, pthread_rwlock_rdlock () and pthread_rwlock_tryrdlock ();
    • Write mode locking, pthread_rwlock_wrlock () and pthread_rwlock_trywrlock ();
    • Unlock operation, pthread_rwlock_unlock ().

3. Condition variable (pthread_cond_t)

Conditional variables used together with mutex locks allow threads to wait for specific conditions in a non-competitive manner. The thread first locks the mutex lock before changing the condition state. Other threads do not notice this change before obtaining the mutex lock. Therefore, the condition can be calculated only after the mutex lock is locked.

Conditional Variable Initialization:

    • Use the constant pthread_cond_initializer to assign the static conditional variable;
    • If the condition variables are dynamically allocated, use the pthread_cond_init () function for initialization. before releasing the underlying memory space, use the pthread_cond_destroy () function to remove the initialization of the condition variables.

Conditional Variable usageFunction pthread_cond_wait () Wait condition is true. The mutex lock in the function protects the condition. The caller passes the lock to the function. The function places the call thread in the list of threads waiting for the condition, and then unlocks the mutex lock. These two operations are atomic operations. When the function returns, it will again obtain control of the mutex lock. The pthread_cond_timedwait () function is added with timeout Processing Based on the processing method that satisfies the pthread_cond_wait () function. If the conditions cannot be met within the specified time, an error code is generated and returned.

Two functions are used to notify the thread that the condition has been met. The pthread_cond_signal () function will wake up a thread waiting for the condition, and the pthread_cond_broadcast () function will wake up all threads waiting for the condition.

Programming example of conditional variables: [Linux programming] use of pthead_cond_t

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.