development using multi-threaded process, it is inevitable that multiple threads concurrently operate the same piece of shared resources, when the operation is all read, there will be no unknown results, once there is a write operation in a thread operation, there will be data out of sync events.
and the reason for the data confusion:
-
Resource sharing (not exclusive resources)
Debug random (competition for data access)
Lack of necessary synchronization mechanisms between threads
above three points, the first two points can not be changed. To improve efficiency, transfer data, resources must be shared. As long as the resources are shared, there will be competition between the threads, so that if there is a competitive relationship, the data will become chaotic.
Therefore, only from the 3rd, so that multiple threads when accessing the shared resources, there is mutual exclusion.
Thread synchronization:
means that only one process is allowed to access a resource for a certain amount of time, and no other thread is allowed to operate on that resource during this time.
synchronization mechanism for threads:
Mutex (mutual exclusion lock)
Each thread needs to get a "lock" before the operation of the resource, after a successful lock to operate, after the operation is unlocked, the other thread can take the lock to operate the resource, if a thread first to get the lock, then take the lock operation will block, the lock directly to the thread to unlock the operation.
Common APIs
initialization: Pthread_mutex_init (pthread_mutex_t*restrict Mutex, const pthread_mutexattr_t *restrict attr);
Static initialization: pthread_mutex_t mutex = Pthread_mutex_initializer;
Release: Pthread_mutex_destroy (pthread_mutex_t *mutex);
The RESTRICT:C99 standard type qualifier, which tells the compiler that the pointing object has been referenced and cannot be modified by any direct or indirect method other than the pointer.
Locking: Pthread_mutex_lock (pthread_mutex_t *mutex);
attempt to lock: Pthread_mutex_trylock (pthread_mutex_t* mutex);
Unlock: Pthread_mutex_unlock (pthread_mutex_t* mutex);
The difference between the Pthread_mutex_lock and Pthread_mutex_trylock is that pthread_mutex_lock if the lock is not acquired will block the wait, and pthread_mutex_ Trylock The lock is not acquired immediately returns the error number (EBUSY).
Direct on case: [Two threads have sequential print Hello wolrd and hello wolrd]
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include < unistd.h> #include <string.h>//global definition mutex pthread_mutex_t mutex;//child thread print Hello worldvoid* tfn (void* Arg) {Srand ( Time (NULL)), while (1) {//Locking Pthread_mutex_lock (&mutex);p rintf ("Hello");//simulates a long-time operation to share a resource, causing the CPU to be easy to master, resulting in an error related to timing sleep ( Rand ()%3);p rintf ("world\n");//Unlock Pthread_mutex_unlock (&mutex); sleep (2);}} int main (int argc, char* argv[]) {pthread_t tid;//random seed srand (time (null));//Mutex initialization pthread_mutex_init (&mutex, NULL) ;//Create Child thread pthread_create (&tid, NULL, TFN, NULL);//parent thread Print Hello Wolrdwhile (1) {//Locking pthread_mutex_lock (&mutex); printf ("HELLO");//simulate long-time operation of shared resources, resulting in CPU-prone, resulting in time-related errors of sleep (rand ()%3);p rintf ("world\n");//Unlock Pthread_mutex_unlock ( &mutex); sleep (2);} return 0;}
read/write Lock:
similar to mutexes, but read-write locks allow for higher parallelism. Its specific: write exclusive, read share . write locks are prioritized when read-write lock contention .
Common APIs
Initialize: Pthread_rwlock_init (pthread_rwlock_t*restrict rwlock, const pthread_mutexattr_t * Restrict attr);
Release: Pthread_rwlock_destroy (pthread_rwlock_t *rwlock);
The RESTRICT:C99 standard type qualifier, which tells the compiler that the pointing object has been referenced and cannot be modified by any direct or indirect method other than the pointer.
Read locking: Pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
attempt to read lock : Pthread_ rwlock _tryrdlock (Pthread_ rwlock _t * rwlock
Write plus Lock: pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);
Try to write lock: pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock);
unlock: Pthread_rwlock_unlock (pthread_rwlock_t* mutex);
Directly on the case: [3 threads write the same global resource on a variable time, and 5 threads read the same global resource on a variable time.]
#include <stdio.h> #include <unistd.h> #include <pthread.h> int counter; //shared Resources Pthread_rwlock_t rwlock; void *th_write (Void *arg) { int t, i = (int) arg; while (1) { //Get write Lock pthread_ Rwlock_wrlock (&rwlock); t = counter; usleep ( printf); ("======= Write %d: %lu: counter=%d ++counter=%d\n ", i,pthread_self (), t, ++counter); //Unlock pthread_rwlock_unlock ( &rwlock); usleep (10000); } &nBsp; return null;} Void *th_read (VOID&NBSP;*ARG) { int i = (int) arg; while (1) { //get read lock pthread_rwlock_rdlock (&rwlock); printf ("- ---------------------------read %d: %lu: %d\n ", i,pthread_self (), counter); //Unlocking pthread_rwlock_unlock (& Rwlock); usleep (+); } return null;} Int main (void) { int i; pthread_t tid[8]; //Initialize read-write lock pthread_rwlock_init (&rwlock, null); //Create 3 Write Threads for (i = 0; i < 3; i++) pthread_create ( &tid[i], NULL, th_write, (void *) i) //Create 5 Read threads for (i = 0; i < 5; i++) pthread_create (&tid[i+3],NULL, th_read, (void *) i); // Wait for all threads to be recycled for (i = 0; i < 8; i++) pthread_join (tid[i],null); //release read/write lock pthread_rwlock_destroy (&rwlock); return 0;}
This article is from the "Sea" blog, be sure to keep this source http://lisea.blog.51cto.com/5491873/1789343
Linux Network programming-----> thread Synchronization One