For multi-threaded synchronization in linux, the lock concept is usually used.
The posix abstracts the structure of a lock type: ptread_mutex_t. Operations on this structure are used to determine whether resources can be accessed. As the name suggests, after a lock, other people cannot open the lock. Only when the lock is not closed (unlock) Can the resource be accessed.
It mainly uses the following five functions.
1: pthread_mutex_init (Pthread_mutex_t* Mutex, const pthread_mutexattr_t * attr );
Initialize the lock variable mutex. Attr is the lock attribute, and NULL is the default attribute.
2: pthread_mutex_lock (Pthread_mutex_t* Mutex); lock
3: pthread_mutex_tylock (Pthread_mutex_t* Mutex); lock, but unlike 2, when the lock is already in use, the return value is EBUSY instead of pending.
4: pthread_mutex_unlock (Pthread_mutex_t* Mutex); release the lock
5: pthread_mutex_destroy (Pthread_mutex_t* Mutex); released after use
In the following typical example, create two threads to add sum from 1 to 100. The first thread starts from 1-49 and then from 50-100. The primary thread reads the final value. To prevent resource competitionPthread_mutex_tLock operation.
#include<stdlib.h>#include<stdio.h>#include<unistd.h>#include<pthread.h>typedef struct ct_sum{int sum;pthread_mutex_t lock;}ct_sum;void * add1(void * cnt){ pthread_mutex_lock(&(((ct_sum*)cnt)->lock)); int i; for( i=0;i<50;i++){ (*(ct_sum*)cnt).sum+=i;} pthread_mutex_unlock(&(((ct_sum*)cnt)->lock)); pthread_exit(NULL); return 0;}void * add2(void *cnt){ int i; cnt= (ct_sum*)cnt; pthread_mutex_lock(&(((ct_sum*)cnt)->lock)); for( i=50;i<101;i++) { (*(ct_sum*)cnt).sum+=i; } pthread_mutex_unlock(&(((ct_sum*)cnt)->lock)); pthread_exit(NULL); return 0;}int main(void){ int i;pthread_t ptid1,ptid2;int sum=0;ct_sum cnt;pthread_mutex_init(&(cnt.lock),NULL);cnt.sum=0;pthread_create(&ptid1,NULL,add1,&cnt);pthread_create(&ptid2,NULL,add2,&cnt);pthread_mutex_lock(&(cnt.lock));printf("sum %d\n",cnt.sum);pthread_mutex_unlock(&(cnt.lock));pthread_join(ptid1,NULL);pthread_join(ptid2,NULL);pthread_mutex_destroy(&(cnt.lock));return 0;}