thread contention problem

Foreword: Resource sharing between threads, so there is no communication problem, but there will be a strong competition problem. There are several ways to solve the competition problem between threads:

1. Mutex

  Function: Ensure that only one thread can operate on shared resources at the same time, but synchronization is not guaranteed

step:

  1.1 Initialize the mutex: (2 methods, generally used static)    

   Dynamic initialization:

      static  pthread_mutex_t     mm;

      prhread_mutex_init(&mm,NULL);

   Static initialization:

      static  pthread_mutex_t    mm=PTHREAD_MUTEX_INITIALIZER;

  1.2 Add/unlock operation

             pthread_mutex_lock(&mm); //Lock operation, the thread that has not acquired the lock will block and wait

     pthread_mutex_trylock(&mm) //Lock operation, the thread that has not acquired the lock will return non-zero, and continue to execute other non-competitive tasks

     pthread_mutex_unlock(&mm) //Unlock operation, the unlock operation will not go wrong, it can be unlocked even if there is no lock

  1.3 Destroying a mutex (lock)

        pthread_mutex_destroy(&mm)//

2. Read-write lock: read-shared and write-exclusive

  Function: Sometimes when multiple threads need to read and write the same resource, there may be problems such as data loss. For example, a read event occurs when writing, and the read-write lock can effectively ensure  read sharing and write exclusive . It is mainly used for There are both reads and writes, and the number of reads is much greater than that of writes

  Note: Each thread should give up its own time slice after execution, which can solve the problem of thread starvation

      sched_yield()        //Abandon cpu scheduling  

  step:

  2.1 Initialize read-write locks (dynamic initialization only)

      static pthread_rwlock_t rw;//Declare a global lock variable

      pthread_rwlock_init(&rw,NULL) //Initialize the lock

  2.2 Add/Unlock

     pthread_rwlock_wrlock(&rw);    //Add a write lock, if the lock fails, it will be blocked here

     pthread_rwlock_trywrlock(&rw) ; //Add a write lock, if the lock fails, it will immediately return a non-zero value to perform other work

     pthread_rwlock_rdlock(&rw);    //Add a read lock, fail to block

     pthread_rwlock_tryrdlock(&rw);  //Add read lock, fail non-blocking

     pthread_rwlock_unlock(&rw); //Unlock (no type and will not fail)

  2.3 Destroying locks

      pthread_rwlock_ destroy(&rw); 

3. Condition variables  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854931&siteId=291194637