转自:https://www.cnblogs.com/farbeyond/p/4482859.html 
作者:farbeyond 

线程中互斥锁使用的步骤与信号量相似!

1、首先定义互斥锁变量,并初始化

pthread_mutex_t mutex_lock;
pthread_mutex_init(&mutex_lock,NULL);
2、在操作前对互斥量进行加锁操作

pthread_mutex_lock(&mutex_lock);
3、操作完毕后进行解锁操作

pthread_mutex_unlock(&mutex_lock);

所有操作均在加锁和解锁操作之间进行,保证同时仅仅对有一个操作对关键变量或是区域进行操作。

下面是自己写的一个小程序,对主函数对变量自加操作,而线程函数进行自减操作。

(该程序有个小bug,看官可执行运行一下,就知道结果了,高手一看就知道问题在哪里,哈哈!卖个关子!)

pthread_mutex_lock(&mutex_lock);对某个互斥锁变量进行加锁操作时,当该变量已经被另外一个线程锁住时,该线程会被阻塞(英文原文为block),可以理解为休眠。
由操作系统基本原理可知,当进程处于就绪状态时,才会获得处理机的时间片,换句话说就是能能被调度到处理机上执行,而阻塞状态则不能。

因此一个线程被阻塞后,将不会执行,处于等待状态,通常是等待某个事件发生或到来。因此,一个对已经加锁的变量进行加锁的线程将被阻塞,其只能等待另外一个线程解锁,才能继续执行。

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <string.h>
  6. #include <errno.h>

  7. void *thread_function(void *arg);
  8. pthread_mutex_t mutex_lock;
  9. int globaltmp=0;
  10. int main(){
  11.     int res;
  12.     pthread_t pthread_tmp;
  13.     pthread_mutex_init(&mutex_lock,NULL);
  14.     pthread_mutex_lock(&mutex_lock);
  15.     res = pthread_create(&pthread_tmp,NULL,thread_function,NULL);
  16.     if(res != 0){
  17.         perror("thread creation failed!");
  18.         exit(EXIT_FAILURE);
  19.     }
  20.     while(1){
  21.         pthread_mutex_unlock(&mutex_lock);
  22.         sleep(2);
  23.         globaltmp++;
  24.         printf("in the main func,globaltmp=%d\n",globaltmp);
  25.          res = pthread_mutex_lock(&mutex_lock);
  26.     // if(res == EDEADLK)
  27.         {
  28.         // printf("it has been locked in the thread!\n");
  29.         }
  30.     // printf(" main func res =%d\n",res);
  31.         sleep(2);
  32.     }
  33.     res = pthread_join(pthread_tmp,NULL);
  34.     if(res != 0 ){
  35.         perror("thread join is failure");
  36.         exit(EXIT_FAILURE);
  37.     }
  38.     printf("thread joined!\n");
  39.     pthread_mutex_destroy(&mutex_lock);
  40.     return 0;
  41. }
  42. void *thread_function(void *arg){
  43.     int res ;
  44.     res = pthread_mutex_lock(&mutex_lock);
  45.     if(res == EDEADLK)
  46.         printf("it has been locked in the main!\n");
  47.     while(1)
  48.     {
  49.         pthread_mutex_unlock(&mutex_lock);
  50.         sleep(1);
  51.         globaltmp--;
  52.         printf("in the pthread func,globaltmp=%d\n",globaltmp);
  53.     // printf("I am in the pthread func\n");
  54.         res = pthread_mutex_lock(&mutex_lock);
  55. // printf("thread func res=%d\n",res);
  56.     // if(res == EDEADLK)
  57.         // printf("it has been locked in the main!\n");
  58.         sleep(1);
  59.     }
  60.     pthread_exit(NULL);
  61. }

09-24 02:42
查看更多