pthread_mutex_lock与pthread_mutex_unlock

pthread互斥锁机制解析

pthread_mutex_lock函数与pthread_mutex_unlock是一般成对使用。pthread_mutex_lock与pthread_mutex_unlock之间代码不会被被别的进程中断。类似原子类的执行。
参考一下代码,当两个线程同时访问cnt时,会发生冲突。

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

#define N 10

int cnt = 0;


void* thread_fun_0(void* arg) {
    for (int i = 0; i < N; ++i) {       
        printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
        ++cnt;        
        usleep(100);
    }
    return NULL;
}

void* thread_fun_1(void* arg) {
    for (int i = 0; i < N; ++i) {     
        printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
        ++cnt;     
        usleep(100);
    }
    return NULL;
}
int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread_fun_0, NULL);
    pthread_create(&t2, NULL, thread_fun_1, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("cnt = %d (expect %d)\n", cnt, 2*N);
   
    return 0;
}

在这里插入图片描述

每个线程是的cnt 递增10次,进程结束cnt应该是20。这次运行结果有问题,按理输出的cnt应该是1~20,不会重复。但是运行结果却重复了,这是因为对cnt更新时没有锁定系统。修改后代码如下:

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

#define N 10
pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
int cnt = 0;


void* thread_fun_0(void* arg) {
    for (int i = 0; i < N; ++i) {
        pthread_mutex_lock(&mux);
        printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
        ++cnt;        
        pthread_mutex_unlock(&mux);
        usleep(100);
    }
    return NULL;
}

void* thread_fun_1(void* arg) {
    for (int i = 0; i < N; ++i) {
        pthread_mutex_lock(&mux);
        printf("thread id[%ld]-----%d\n",pthread_self(),cnt);
        ++cnt;        
        pthread_mutex_unlock(&mux);
        usleep(100);
    }
    return NULL;
}
int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread_fun_0, NULL);
    pthread_create(&t2, NULL, thread_fun_1, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("cnt = %d (expect %d)\n", cnt, 2*N);
    pthread_mutex_destroy(&mux);
    return 0;
}

在这里插入图片描述
本次的运行结果很理想,没有出现冲突。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值