#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
最新推荐文章于 2022-04-27 10:30:37 发布