#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define true 1
#define false 0
static int gCnt = 0;
static pthread_mutex_t gMutex;
#define LOCK \
pthread_mutex_lock(&gMutex)
#define UNLOCK \
pthread_mutex_unlock(&gMutex)
void* pFunc_1(void *p){
while(true){
sleep(1);
LOCK;
printf("tid1 get lock\r\n");
printf("tid1 ::%d\r\n",gCnt++);
printf("tid1 unlock\r\n");
UNLOCK;
}
}
void* pFunc_2(void *p){
sleep(1);
while(true){
sleep(5);
LOCK;
printf("tid2 get lock\r\n");
sleep(4);
printf("tid2 ::%d\r\n",gCnt);
printf("tid2 unlock\r\n");
UNLOCK;
}
}
int main(){
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,pFunc_1,NULL);
pthread_create(&tid2,NULL,pFunc_2,NULL);
printf("wait the sub threads::%d,%d..\r\n",tid1,tid2);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}myPthread_mutext.c
最新推荐文章于 2023-11-23 16:12:01 发布
本文通过C语言实现了一个使用互斥锁保护共享资源的多线程程序示例。两个线程分别以不同的频率更新和读取全局变量,并在操作过程中使用互斥锁来避免竞态条件。
2542

被折叠的 条评论
为什么被折叠?



