|  | 
 
| 下面通过一系列实验,说明线程互斥锁的应用。 
 实验一:互斥锁的阻塞
 代码如下:
 
 运行与输出:#include <stdlib.h>#include <pthread.h>
 #include <semaphore.h>
 #include <string.h>
 
 void *thread_function (void *arg);
 pthread_mutex_t work_mutex;     //全局互斥锁对象
 
 #define WORK_SIZE 1024
 char work_area[WORK_SIZE];
 int time_to_exit = 0;
 
 int main (int argc, char *argv[])
 {
 int res;
 pthread_t a_thread;
 void *thread_result;
 
 res = pthread_mutex_init (&work_mutex, NULL);   //初始化互斥锁
 if (res != 0) {
 printf ("Mutex initialization failed");
 exit (EXIT_FAILURE);
 }
 res = pthread_create (&a_thread, NULL, thread_function, NULL);
 if (res != 0) {
 printf ("Thread creation failed");
 exit (EXIT_FAILURE);
 }
 pthread_mutex_lock (&work_mutex);
 printf ("等待全部变量 time_to_exit 的变为 1\n");
 
 while (!time_to_exit) {
 printf ("还没改变,继续等待 3s ...\n");
 sleep(3);
 }
 
 pthread_mutex_unlock (&work_mutex);
 pthread_mutex_destroy (&work_mutex);
 pthread_join (a_thread, &thread_result);
 
 return (0);
 }
 
 void *thread_function (void *arg)
 {
 sleep(1);
 pthread_mutex_lock (&work_mutex);
 printf ("资源没有释放,无法打印此行信息\n");
 time_to_exit = 1;
 }
说明:> ./pthread_lock 等待全部变量 time_to_exit 的变为 1
 还没改变,继续等待 3s ...
 还没改变,继续等待 3s ...
 还没改变,继续等待 3s ...
 ... ... ...
从输出可见,会一直输出“还没改变,继续等待 3s ...”。
 代码中, 经过 pthread_create() 函数后,会创建一个新的线程,然后这个线程就会去执行线程指定函数 thread_function(),在这个函数的开始,我们故意使用一个 sleep() 函数使进程睡眠 1 秒,目的是让主线程申请到互斥锁。由于主线程也在等待子线程改变全局变量time_to_exit,而子线程又申请不到互斥锁(被阻塞),所以两者之间形成死锁。故而看到不断输出的结果。
 | 
 |