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

tech2025-11-10  7

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

#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)