互斥锁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()。