linux线程同步-互斥锁-附可运行源码

线程同步,即为多个线程在操作同一个公共数据区域时,能保持数据的一致性,看下面代码:

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

int num = 100;

void*mythread(void* p)
{
        srand(time(NULL));
        while(1)
        {
                num = num + 1;
                printf("hello, num = %d", num);
                sleep(rand()%2);                //模拟让其他线程抢去cpu时间
                printf("world, num = %d\n", num);
                sleep(rand()%2);
        }
}

int main()
{
        srand(time(NULL));
        pthread_t t1;
        pthread_create(&t1,NULL, mythread, NULL);

        while(1)
        {
                num = num + 1;
                printf("HELLO, num = %d", num);
                sleep(rand()%2);
                printf("WORLD, num = %d\n", num);
                sleep(rand()%2);
        }
        pthread_join(t1, NULL);
        return 0;
}

我们希望的结果是主线程中输出num和t1线程中的num是不一样的,同时在一个while的结构体中,num应该是一样的,那么,看下面的输出结果:
在这里插入图片描述
这个结果并不是我们想要的输出。
要正确输出结果,需要在操作数据加上锁,只有拿到锁的线程才能对公共数据进行操作。
先说一下互斥锁,主要操作函数有:

pthread_mutex_init		//初始化互斥锁
pthread_mutex_destroy	//销毁锁
pthread_mutex_lock		//加锁
pthread_mutex_trylock	//加锁
pthread_mutex_unlock	//解锁

以上5个函数返回值都是:成功返回0,失败返回错误号。
再者,pthread_mutex_t类型,其本质是一个结构体,为简化理解,应用可忽略其实现细节,简单单程整数看待。
pthread_mutex_t mutex: 变量mutex只有两种取值1,0

那么,我们在操作公共区域加锁,代码如下:

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

pthread_mutex_t lock;
int num = 100;

void*mythread(void* p)
{
        srand(time(NULL));
        while(1)
        {
                pthread_mutex_lock(&lock);
                num = num + 1;
                printf("hello, num = %d", num);
                sleep(rand()%2);                //模拟让其他线程抢去cpu时间
                printf("world, num = %d\n", num);
                pthread_mutex_unlock(&lock);
                sleep(rand()%2);
        }
}


int main()
{
        pthread_mutex_init(&lock, NULL);
        srand(time(NULL));
        pthread_t t1;
        pthread_create(&t1,NULL, mythread, NULL);

        while(1)
        {
                pthread_mutex_lock(&lock);
                num = num + 1;
                printf("HELLO, num = %d", num);
                sleep(rand()%2);
                printf("WORLD, num = %d\n", num);
                pthread_mutex_unlock(&lock);
                sleep(rand()%2);

        }

        pthread_join(t1, NULL);

        pthread_mutex_destroy(&lock);
        return 0;
}

运行结果如下:

在这里插入图片描述
从上面结果看,主线性和子线程,要在拿到锁之后才进行数据操作,这样就保证了数据同步。

也可关注微信公众号,欢迎交流。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值