互斥锁pthread_mutex_trylock()线程同步失败

互斥锁pthread_mutex_trylock()加锁之后不能同步
线程同步,指一个线程发出某一功能调用时,在没有得到结果之前,该调用不返回。同时其它线程为保证数据一致性,不能调用该功能。

数据混乱的原因
资源共享(独享资源则不会)
调度随机(线程操作共享资源的先后顺序不确定)
线程间缺乏必要的同步机制。

同步即协同步调,按预定的先后次序运行。
互斥量mutex
如果锁是锁着的:
- 线程阻塞,阻塞在这把锁上
如果锁是打开的:
- 线程访问共享资源
- 会将这把锁上锁

关于互斥锁pthread_mutex_trylock()加锁之后依然不能同步问题,有错误

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>

#define MAX 1000
// 全局变量
int number;
// 创建一把互斥锁
pthread_mutex_t mutex;

// 线程处理函数
void* funcA_num(void* arg)
{
    for(int i=0; i<MAX; ++i)
    {
        // 访问全局变量之前加锁
        if(pthread_mutex_trylock(&mutex) == 0)
        {
			int cur = number;
			cur++;
			number = cur;
			printf("Thread A, id = %lu, number = %d\n", pthread_self(), number);
			// 解锁
			pthread_mutex_unlock(&mutex);
        }
		usleep(5);
    }
    return NULL;
}

void* funcB_num(void* arg)
{
    for(int i=0; i<MAX; ++i)
    {
        if(pthread_mutex_trylock(&mutex) == 0)
        {
			int cur = number;
        	cur++;
			number = cur;
			printf("Thread B, id = %lu, number = %d\n", pthread_self(), number);
			pthread_mutex_unlock(&mutex);
        }
    	usleep(5);
    }
    return NULL;
}

int main(int argc, const char* argv[])
{
    pthread_t p1, p2;
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    // 创建两个子线程
    pthread_create(&p1, NULL, funcA_num, NULL);
    pthread_create(&p2, NULL, funcB_num, NULL);

    // 阻塞,资源回收
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);

    // 释放互斥锁资源
    pthread_mutex_destroy(&mutex);
    return 0;
}

结果如下,依旧没有同步:

Thread B, id = 140157124380416, number = 1733
Thread B, id = 140157124380416, number = 1734
Thread B, id = 140157124380416, number = 1735

结论:pthread_mutex_trylock()加锁失败直接返回错误号(如:EBUSY),不阻塞,跳过了本次循环的 +1 执行操作,出现错误,尽量用pthread_mutex_lock()替代pthread_mutex_trylock()。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值