Linux 多任务编程——线程同步与互斥:互斥锁

为什么需要互斥锁?
在多任务操作系统中,同时运行的多个任务可能都需要使用同一种资源。这个过程有点类似于,公司部门里,我在使用着打印机打印东西的同时(还没有打印完),别人刚好也在此刻使用打印机打印东西,如果不做任何处理的话,打印出来的东西肯定是错乱的。

下面我们用程序模拟一下这个过程,线程一需要打印“ hello ”,线程二需要打印“ world ”,不加任何处理的话,打印出来的内容会错乱:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
 
// 打印机
void printer(char *str)
{
    while(*str!='\0')
    {
        putchar(*str);    
        fflush(stdout);
        str++;
        sleep(1);
    }
    printf("\n"); 
}
 
// 线程一
void *thread_fun_1(void *arg)
{
    char *str = "hello";
    printer(str); //打印
}
 
// 线程二
void *thread_fun_2(void *arg)
{
    char *str = "world";
    printer(str); //打印
}
 
int main(void)
{
    pthread_t tid1, tid2;
    
    // 创建 2 个线程
    pthread_create(&tid1, NULL, thread_fun_1, NULL);
    pthread_create(&tid2, NULL, thread_fun_2, NULL);
 
    // 等待线程结束,回收其资源
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL); 
    
    return 0;
}

运行结果如下:


实际上,打印机是有做处理的,我在打印着的时候别人是不允许打印的,只有等我打印结束后别人才允许打印。这个过程有点类似于,把打印机放在一个房间里,给这个房间安把锁,这个锁默认是打开的。当 A 需要打印时,他先过来检查这把锁有没有锁着,没有的话就进去,同时上锁在房间里打印。而在这时,刚好 B 也需要打印,B 同样先检查锁,发现锁是锁住的,他就在门外等着。而当 A 打印结束后,他会开锁出来,这时候 B 才进去上锁打印。

而在线程里也有这么一把锁——互斥锁(mutex),互斥锁是一种简单的加锁的方法来控制对共享资源的访问,互斥锁只有两种状态,即上锁( lock )和解锁( unlock )

互斥锁的操作流程如下:

1)在访问共享资源后临界区域前,对互斥锁进行加锁。

2)在访问完成后释放互斥锁导上的锁。

3)对互斥锁进行加锁后,任何其他试图再次对互斥锁加锁的线程将会被阻塞,直到锁被释放。

 

互斥锁基本操作

互斥锁的数据类型是: pthread_mutex_t。
函数需要的头文件:#include <pthread.h>

 

1)初始化互斥锁

int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

功能:

初始化一个互斥锁。

参数:

mutex:互斥锁地址。类型是 pthread_mutex_t 。
attr:设置互斥量的属性,通常可采用默认属性,即可将 attr 设为 NULL。

返回值:

成功:0,成功申请的锁默认是打开的。

失败:非 0 错误码

可以使用宏 PTHREAD_MUTEX_INITIALIZER 静态初始化互斥锁,比如:
pthread_mutex_t  mutex = PTHREAD_MUTEX_INITIALIZER;
这种方法等价于使用 NULL 指定的 attr 参数调用 pthread_mutex_init() 来完成动态初始化,不同之处在于 PTHREAD_MUTEX_INITIALIZER 宏不进行错误检查

 

2)上锁

int pthread_mutex_lock(pthread_mutex_t *mutex);

功能:

对互斥锁上锁,若互斥锁已经上锁,则调用者一直阻塞,直到互斥锁解锁后再上锁。

参数:

mutex:互斥锁地址。

返回值:

成功:0

失败:非 0 错误码

 

int pthread_mutex_trylock(pthread_mutex_t *mutex);

调用该函数时,若互斥锁未加锁,则上锁,返回 0;若互斥锁已加锁,则调用者不阻塞,函数直接返回失败,即 EBUSY。

 

3)解锁

int pthread_mutex_unlock(pthread_mutex_t * mutex);

功能:

对指定的互斥锁解锁。

参数:

mutex:互斥锁地址。

返回值:

成功:0

失败:非 0 错误码

 

4)销毁互斥锁

int pthread_mutex_destroy(pthread_mutex_t *mutex);

功能:

销毁指定的一个互斥锁。互斥锁在使用完毕后,必须要对互斥锁进行销毁,以释放资源。

参数:

mutex:互斥锁地址。

返回值:

成功:0

失败:非 0 错误码

 

互斥锁应用实例

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
 
pthread_mutex_t mutex; //互斥锁
 
// 打印机
void printer(char *str)
{
    pthread_mutex_lock(&mutex); //上锁
    while(*str!='\0')
    {
        putchar(*str);    
        fflush(stdout);
        str++;
        sleep(1);
    }
    printf("\n"); 
    pthread_mutex_unlock(&mutex); //解锁
}
 
// 线程一
void *thread_fun_1(void *arg)
{
    char *str = "hello";
    printer(str); //打印
}
 
// 线程二
void *thread_fun_2(void *arg)
{
    char *str = "world";
    printer(str); //打印
}
 
int main(void)
{
    pthread_t tid1, tid2;
    
    pthread_mutex_init(&mutex, NULL); //初始化互斥锁
    
    // 创建 2 个线程
    pthread_create(&tid1, NULL, thread_fun_1, NULL);
    pthread_create(&tid2, NULL, thread_fun_2, NULL);
 
    // 等待线程结束,回收其资源
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL); 
    
    pthread_mutex_destroy(&mutex); //销毁互斥锁
    
    return 0;
}

运行结果如下:

 

--------------------- 
作者:Mike__Jiang 
来源:CSDN 
原文:https://blog.csdn.net/tennysonsky/article/details/46494077 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值