关闭

嵌入式 Linux C 多线程编程 互斥锁与条件变量

750人阅读 评论(0) 收藏 举报
分类:

一、互斥锁
 
互斥量从本质上说就是一把锁, 提供对共享资源的保护访问。
 
  1. 初始化:
 
  在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化:
 
  对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER,或者调用pthread_mutex_init.
 
  对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init进行初始化,并且在释放内存(free)前需要调用pthread_mutex_destroy.
 
  原型:
 
  int pthread_mutex_init(pthread_mutex_t *restrict mutex, constpthread_mutexattr_t *restric attr);

  int pthread_mutex_destroy(pthread_mutex_t *mutex);

  头文件:
 
  返回值: 成功则返回0, 出错则返回错误编号.
 
  说明: 如果使用默认的属性初始化互斥量, 只需把attr设为NULL. 其他值在以后讲解。
 
  2. 互斥操作:
 
  对共享资源的访问, 要对互斥量进行加锁, 如果互斥量已经上了锁, 调用线程会阻塞, 直到互斥量被解锁.在完成了对共享资源的访问后, 要对互斥量进行解锁。
 
  首先说一下加锁函数:
 
  头文件:
 
  原型:
 
  int pthread_mutex_lock(pthread_mutex_t *mutex);

  int pthread_mutex_trylock(pthread_mutex_t *mutex);
 
  返回值: 成功则返回0, 出错则返回错误编号.
 
  说明: 具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住,trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了,trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态。
 
  再说一下解所函数:
 
  头文件:
 
  原型: int pthread_mutex_unlock(pthread_mutex_t *mutex);
 
  返回值: 成功则返回0, 出错则返回错误编号.
 
  3. 死锁:
 
  死锁主要发生在有多个依赖锁存在时, 会在一个线程试图以与另一个线程相反顺序锁住互斥量时发生.如何避免死锁是使用互斥量应该格外注意的东西。
 
  总体来讲, 有几个不成文的基本原则:
 
  对共享资源操作前一定要获得锁。
 
  完成操作以后一定要释放锁。
 
  尽量短时间地占用锁。
 
  如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC。
 
  线程错误返回时应该释放它所获得的锁。
 
下面给个测试小程序进一步了解互斥,mutex互斥信号量锁住的不是一个变量,而是阻塞住一段程序。如果对一个mutex变量testlock,执行了第一次pthread_mutex_lock(testlock)之后,在unlock(testlock)之前的这段时间内,如果有其他线程也执行到了pthread_mutex_lock(testlock),这个线程就会阻塞住,直到之前的线程unlock之后才能执行,由此,实现同步,也就达到保护临界区资源的目的。
#include
#include

static pthread_mutex_t testlock;
pthread_t test_thread;

void *test()
{
pthread_mutex_lock(&testlock);
printf("thread Test() \n");
pthread_mutex_unlock(&testlock);
}

int main()
{
pthread_mutex_init(&testlock, NULL);
pthread_mutex_lock(&testlock);

printf("Main lock \n");

pthread_create(&test_thread, NULL, test, NULL);
sleep(1); //更加明显的观察到是否执行了创建线程的互斥锁
printf("Main unlock \n");
pthread_mutex_unlock(&testlock);

sleep(1);
 
pthread_join(test_thread,NULL);
pthread_mutex_destroy(&testlock);
return 0;
}

make
gcc -D_REENTRANT -lpthread -o test test.c

结果:
Main lock
Main unlock
thread Test()

一、练习要求

三个线程访问一个全局共享的字符串,thread1访问时会在这个字符串末尾追加'1'字符,thread2访问时会在这个字符串末尾追加'2'字符,thread3访问时会在这个字符串末尾追加'3‘字符。要求:thread1-thread2-thread3依次访问,最终字符串的内容为"123"。

二、第一阶段

在main函数中,开启这三个线程。并没有为线程访问共享数据加锁和同步。在main函数中sleep(3)来避免主线程过早地退出。

【实现代码】

  1. #include
  2. #include
  3. #include
  4. #include
  5. #include
  6. #include
  7. char g_array[5]={'\0'};
  8. void*thread1(void*);
  9. void*thread2(void*);
  10. void*thread3(void*);
  11. int main(int argc,char**argv)
  12. {
  13. printf("[enter main ]\n");
  14. pthread_t tid1, tid2, tid3;
  15. int rc1=0, rc2=0,rc3=0;
  16. rc3 = pthread_create(&tid3, NULL, thread3,NULL);
  17. if(rc3 !=0)
  18. printf("%s:%d\n",__func__,strerror(rc3));
  19. rc2 = pthread_create(&tid2, NULL, thread2,NULL);
  20. if(rc2 !=0)
  21. printf("%s:%d\n",__func__,strerror(rc2));
  22. rc1 = pthread_create(&tid1, NULL, thread1,&tid2);
  23. if(rc1 !=0)
  24. printf("%s:%d\n",__func__,strerror(rc1));
  25. sleep(3);
  26. printf("[ leave main]\n");
  27. exit(0);
  28. }
  29. void*thread1(void*arg)
  30. {
  31. printf("[ enter thread1]\n");
  32. printf("thisis thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  33. int index =strlen(g_array);
  34. g_array[index] = '1';
  35. printf("this is thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  36. printf("[leave thread1 ]\n");
  37. pthread_exit(0);
  38. }
  39. void*thread2(void*arg)
  40. {
  41. printf("[enter thread2 ]\n");
  42. printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  43. int index =strlen(g_array);
  44. g_array[index] = '2';
  45. printf("thisis thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  46. printf("[ leave thread2]\n");
  47. pthread_exit(0);
  48. }
  49. void*thread3(void*arg)
  50. {
  51. printf("[ enter thread3]\n");
  52. printf("thisis thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  53. int index =strlen(g_array);
  54. g_array[index] = '3';
  55. printf("this is thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  56. printf("[leave thread3 ]\n");
  57. pthread_exit(0);
  58. }
#include
#include
#include
#include
#include
#include

char g_array[5]= {'\0'};

void* thread1(void*);
void* thread2(void*);
void* thread3(void*);

int main(int argc, char** argv)
{
        printf("[ enter main ]\n");
        pthread_t tid1, tid2, tid3;
        int rc1=0, rc2=0, rc3=0;

        rc3 = pthread_create(&tid3, NULL, thread3, NULL);
        if(rc3 != 0)
                printf("%s: %d\n",__func__, strerror(rc3));

        rc2 = pthread_create(&tid2, NULL, thread2, NULL);
        if(rc2 != 0)
                printf("%s: %d\n",__func__, strerror(rc2));

        rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
        if(rc1 != 0)
                printf("%s: %d\n",__func__, strerror(rc1));

        sleep(3);
        printf("[ leave main ]\n");
        exit(0);
}

void* thread1(void* arg)
{
        printf("[ enter thread1 ]\n");
        printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        int index = strlen(g_array);
        g_array[index] = '1';
        printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        printf("[ leave thread1 ]\n");
        pthread_exit(0);
}

void* thread2(void* arg)
{
        printf("[ enter thread2 ]\n");
        printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        int index = strlen(g_array);
        g_array[index] = '2';
        printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        printf("[ leave thread2 ]\n");
        pthread_exit(0);
}

void* thread3(void* arg)
{
        printf("[ enter thread3 ]\n");
        printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        int index = strlen(g_array);
        g_array[index] = '3';
        printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        printf("[ leave thread3 ]\n");
        pthread_exit(0);
}

【编译和运行命令】

gcc -lpthreadThreadTest_1.c

./a.out

【运行结果】
[ enter main ]
[ enter thread1 ]
[ enter thread3 ]
[ enter thread2 ]
this is thread1, g_array: , thread id is 3060820848
this is thread2, g_array: , thread id is 3069213552
this is thread2, g_array: 12, thread id is 3069213552
[ leave thread2 ]
this is thread3, g_array: 12, thread id is 3077606256
this is thread3, g_array: 123, thread id is 3077606256
[ leave thread3 ]
this is thread1, g_array: 123, thread id is 3060820848
[ leave thread1 ]
[ leave main ]

二、第二阶段

为线程访问共享数据加锁和同步

1. thread1访问共享数据完毕后让cond1条件为真;

2. thread2等待cond1条件为真后才进行数据访问,访问数据完毕时让cond2条件为真;

3. thread3等待cond2条件为真后才进行数据访问,访问数据完毕时让cond3条件为真;

4.主线程等待cond3条件为真才退出。

注意:在对临界资源进行操作之前需要加锁,操作完解锁使用条件变量可以以原子方式阻塞线程,直到某个特定条件为真为止。

为什么条件变量始终与互斥锁一起使用,对条件的测试是在互斥锁(互斥)的保护下进行的呢?

因为“某个特性条件”通常是在多个线程之间共享的某个变量。互斥锁允许这个变量可以在不同的线程中设置和检测。

【实现代码】

  1. #include
  2. #include
  3. #include
  4. #include
  5. #include
  6. #include
  7. char g_array[5]={'\0'};
  8. static pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER; //mutex
  9. static pthread_cond_t cond1= PTHREAD_COND_INITIALIZER; //cond
  10. static pthread_cond_t cond2= PTHREAD_COND_INITIALIZER; //cond
  11. static pthread_cond_t cond3=PTHREAD_COND_INITIALIZER; //cond
  12. static pthread_cond_tcond_main_exit= PTHREAD_COND_INITIALIZER; //cond
  13. void*thread1(void*);
  14. void*thread2(void*);
  15. void*thread3(void*);
  16. int main(int argc,char**argv)
  17. {
  18. printf("[ enter main]\n");
  19. pthread_t tid1, tid2, tid3;
  20. int rc1=0, rc2=0,rc3=0;
  21. rc3 = pthread_create(&tid3, NULL, thread3,NULL);
  22. if(rc3 !=0)
  23. printf("%s:%d\n",__func__,strerror(rc3));
  24. rc2 = pthread_create(&tid2, NULL, thread2,NULL);
  25. if(rc2 !=0)
  26. printf("%s:%d\n",__func__,strerror(rc2));
  27. rc1 = pthread_create(&tid1, NULL, thread1,&tid2);
  28. if(rc1 !=0)
  29. printf("%s:%d\n",__func__,strerror(rc1));
  30. pthread_mutex_lock(&mutex);
  31. pthread_cond_wait(&cond3,&mutex);
  32. pthread_mutex_unlock(&mutex);
  33. printf("[ leave main]\n");
  34. exit(0);
  35. }
  36. void*thread1(void*arg)
  37. {
  38. printf("[ enter thread1]\n");
  39. pthread_mutex_lock(&mutex);
  40. //printf("this is thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  41. int index =strlen(g_array);
  42. sleep(5);
  43. if(index ==0)
  44. {
  45. g_array[index] = '1';
  46. }
  47. printf("thisis thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  48. pthread_cond_signal(&cond1);
  49. pthread_mutex_unlock(&mutex);
  50. printf("[leave thread1 ]\n");
  51. pthread_exit(0);
  52. }
  53. void*thread2(void*arg)
  54. {
  55. printf("[enter thread2 ]\n");
  56. pthread_mutex_lock(&mutex); // why cant lock ???
  57. pthread_cond_wait(&cond1,&mutex);
  58. //printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  59. int index =strlen(g_array);
  60. sleep(3);
  61. if(index ==1)
  62. {
  63. g_array[index] = '2';
  64. }
  65. printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  66. pthread_cond_signal(&cond2);
  67. pthread_mutex_unlock(&mutex);
  68. printf("[ leave thread2]\n");
  69. pthread_exit(0);
  70. }
  71. void*thread3(void*arg)
  72. {
  73. printf("[ enter thread3]\n");
  74. pthread_mutex_lock(&mutex);
  75. pthread_cond_wait(&cond2,&mutex);
  76. //printf("this is thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  77. int index =strlen(g_array);
  78. if(index ==2)
  79. {
  80. g_array[index] = '3';
  81. pthread_cond_signal(&cond3);
  82. }
  83. printf("thisis thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
  84. pthread_mutex_unlock(&mutex);
  85. printf("[leave thread3 ]\n");
  86. pthread_exit(0);
  87. }
#include
#include
#include
#include
#include
#include

char g_array[5]= {'\0'};

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //mutex
static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; //cond
static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; //cond
static pthread_cond_t cond3= PTHREAD_COND_INITIALIZER; //cond

static pthread_cond_t cond_main_exit= PTHREAD_COND_INITIALIZER; //cond

void* thread1(void*);
void* thread2(void*);
void* thread3(void*);

int main(int argc, char** argv)
{
        printf("[ enter main ]\n");
        pthread_t tid1, tid2, tid3;
        int rc1=0, rc2=0, rc3=0;

        
        rc3 = pthread_create(&tid3, NULL, thread3, NULL);
        if(rc3 != 0)
                printf("%s: %d\n",__func__, strerror(rc3));
        
        rc2 = pthread_create(&tid2, NULL, thread2, NULL);
        if(rc2 != 0)
                printf("%s: %d\n",__func__, strerror(rc2));

        rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
        if(rc1 != 0)
                printf("%s: %d\n",__func__, strerror(rc1));

        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond3, &mutex);
        pthread_mutex_unlock(&mutex);
        printf("[ leave main ]\n");
        exit(0);

        
}

void* thread1(void* arg)
{
        printf("[ enter thread1 ]\n");
        
        pthread_mutex_lock(&mutex);
        //printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        int index = strlen(g_array);
        sleep(5);
        if(index == 0)
        {
                g_array[index] = '1';
                
        }
        printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        pthread_cond_signal(&cond1);
        pthread_mutex_unlock(&mutex);
        
        printf("[ leave thread1 ]\n");
        pthread_exit(0);
}

void* thread2(void* arg)
{
        

        printf("[ enter thread2 ]\n");
        
        pthread_mutex_lock(&mutex); // why cant lock ???
        pthread_cond_wait(&cond1, &mutex);
        //printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());      
        int index = strlen(g_array);
        sleep(3);
        if(index == 1)
        {
                g_array[index] = '2';   
        }
        printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        pthread_cond_signal(&cond2);
        pthread_mutex_unlock(&mutex);
        
        printf("[ leave thread2 ]\n");
        pthread_exit(0);
}

void* thread3(void* arg)
{
        printf("[ enter thread3 ]\n");
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond2, &mutex);
        //printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        
        int index = strlen(g_array);
        if(index == 2)
        {
                g_array[index] = '3';
                pthread_cond_signal(&cond3);
        }
        printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
        pthread_mutex_unlock(&mutex);
        printf("[ leave thread3 ]\n");
        pthread_exit(0);
}

【运行结果】

[ enter main ]
[ enter thread3 ]
[ enter thread2 ]
[ enter thread1 ]
this is thread1, g_array: 1, thread id is 3065633680
[ leave thread1 ]
this is thread2, g_array: 12, thread id is 3076123536
[ leave thread2 ]
this is thread3, g_array: 123, thread id is 3086613392
[ leave thread3 ]
[ leave main ]

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:979952次
    • 积分:17636
    • 等级:
    • 排名:第540名
    • 原创:741篇
    • 转载:522篇
    • 译文:0篇
    • 评论:105条
    最新评论