曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4079|回复: 0
打印 上一主题 下一主题

线程互斥锁实验

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2010-6-3 22:34:48 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
下面通过一系列实验,说明线程互斥锁的应用。

实验一:互斥锁的阻塞
代码如下:
#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,而子线程又申请不到互斥锁(被阻塞),所以两者之间形成死锁。故而看到不断输出的结果。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-3 13:04 , Processed in 0.064420 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表