互斥锁的使用

多线程问题中为了避免读取脏数据等问题的发生,在某一个函数需要对共享数据空间操作时需要引入锁的概念。即当某个操作要对文件读写时需要加锁以防止在操作期间其它函数对数据修改或者读取等导致获得脏数据的问题。

  • 互斥锁的定义
pthread_mutex_t mutex;

在使用互斥锁之前需要初始化变量;

  • 互斥锁的初始化
pthread_mutex_init(&mutex,NULL);

第一个参数是定义的互斥锁地址,第二个参数是锁的属性没有可以传NULL;
当对某一块数据操作之前需要加锁

  • 加锁
pthread_mutex_lock(&mutex);

传入参数是定义的互斥锁地址;
对数据操作完后应该尽快解除锁让其它程序使用

  • 解锁
pthread_mutex_unlock(&mutex);

参数为定义的互斥锁地址;
加锁和解锁应该尽可能的小即用时加锁,用完后尽快解锁。当程序结束时需要销毁互斥锁

  • 互斥锁销毁
pthread_mutex_unlock(&mutex);

参数为定义的互斥锁地址。
完整实例代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<sched.h>

void *producter_f(void *arg);
void *consumer_f(void *arg);
int buffer_has_item=0;
pthread_mutex_t mutex;
int running=1;

int main(int argc, char const *argv[])
{
    pthread_t consumer_t;
    pthread_t producter_t;

    //初始化互斥量
    pthread_mutex_init(&mutex,NULL);

    pthread_create(&producter_t,NULL,(void *)producter_f,NULL);
    pthread_create(&consumer_t,NULL,(void *)consumer_f,NULL);

    //等待线程创建完毕
    sleep(10);
    running=0;

    pthread_join(consumer_t,NULL);
    pthread_join(producter_t,NULL);

    pthread_mutex_destroy(&mutex);

    return 0;
}

void *producter_f(void *arg){
    while (running)
    {
        pthread_mutex_lock(&mutex);
        printf("producter create item:%d\n",++buffer_has_item);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    
    return NULL;
}

void *consumer_f(void *arg){
    while (running)
    {
        pthread_mutex_lock(&mutex);
        printf("consumer eat item:%d\n",buffer_has_item--);
        pthread_mutex_unlock(&mutex);
        sleep(2);
    }

    return NULL;
}

makefile文件内容如下:

src=$(wildcard *.c)
obj=$(patsubst %.c,%.o,$(src))

ALL:$(obj)

$(obj):%.o:%.c
	gcc $< -o $@ -g

clean:
	-rm -fr $(obj) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值