linux 通过互斥量实现线程同步

    在计算机中,通常是多线程同时执行,线程均可访问进程的资源,因此当这些线程并发访问临界资源时,如果不进行线程同步,将会导致错误发生,程序运行结果出现不可预知的错误,但往往这些错误无法重现,并且程序正确运行。linux提供了互斥量来控制线程对临界资源的访问,即通过对互斥量进行加锁解锁。 

    下面程序实现四个数相加。首先在主线程中创建了两个线程分别执行run1,和run2。这两个线程在执行的过程中都会访问临界资源a,b,以及calculate_sum方法,两个线程同时执行。假设,当同时访问a时,线程1将2赋值给了a,线程2在其后又将4赋给了a,那么a的值便改变了,而线程1运行的结果便改变了。

    因此,在我们不知道线程运行顺序的时候,通过定义信号量,对要访问的临界资源进行加锁解锁操作。在线程中对a,b,以及calculate_sum方法进行加锁,在访问完后再对其进行解锁操作,便可实现线程同步。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<pthread.h>
#include<unistd.h>
typedef unsigned int u32;
pthread_t ntid1;
pthread_t ntid2;
void calculate_sum(int a,int b,const char*);
void *run1(void *);
void *run2(void *);

int main(){
    int err1,err2;
    err1 = pthread_create(&ntid1,NULL,run1,NULL);
    err2 = pthread_create(&ntid2,NULL,run2,NULL);
    sleep(2);

    return 0;
}

int sum = 0;
int a = 0;
int b = 0;


pthread_mutex_t mqlock =  PTHREAD_MUTEX_INITIALIZER;


void calculate_sum(int a,int b,const char *s){
    sum =sum +  a + b;
    printf("%s: sum = %d\n",s,sum);
}

void *run1(void *arg){
    pthread_mutex_lock(&mqlock); 
    a = 2;
    b = 5;
    sleep(1);
    calculate_sum(a,b,"run1");
    pthread_mutex_unlock(&mqlock);
}

void *run2(void *arg){
    pthread_mutex_lock(&mqlock);
    a  = 4;
    b  = 4;
    calculate_sum(a,b,"run2");
    pthread_mutex_unlock(&mqlock);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值