第一题:测试错误检查锁和递归锁是否会造成死锁状态
pthread_mutex_t at1;
pthread_mutex_t at2;
void* run(void* data)
{
while(1)
{
pthread_mutex_lock(&at2);
printf("2\n");
}
}
int main(int argc, const char *argv[])
{
pthread_mutexattr_t attrmutex;
pthread_mutexattr_init(&attrmutex);
//pthread_mutexattr_settype(&attrmutex,PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutexattr_settype(&attrmutex,PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init(&at1,&attrmutex);
pthread_mutex_init(&at2,&attrmutex);
pthread_mutexattr_destroy(&attrmutex);
pthread_t thid;
pthread_create(&thid,0,run,0);
pthread_detach(thid);
while(1)
{
pthread_mutex_lock(&at1);
printf("1\n");
}
return 0;
}
第二题:有2条隧道,一条快速隧道,一条普通隧道。有5列火车,3列复兴号,2列绿皮扭扭车 要求,复兴号2条隧道都能走,绿皮车只能走普通隧道,模拟火车过隧道的场景
pthread_mutex_t m1;
pthread_mutex_t m2;
void* run1(void* arg)
{
while(1){
pthread_mutex_lock(&m1);
printf("绿皮车占据了慢速隧道\n");
sleep(1);
pthread_mutex_unlock(&m1);
usleep(100000);
}
}
void* run2(void* arg)
{
while(1){
int i=rand()%2+1;
if(i==1){
int res=pthread_mutex_trylock(&m1);
if(res!=0)continue;
printf("高铁占据了慢速隧道\n");
sleep(2);
pthread_mutex_unlock(&m1);
}else{
pthread_mutex_lock(&m2);
printf("高铁占据了快速隧道\n");
sleep(2);
pthread_mutex_unlock(&m2);
}
}
}
int main(int argc, const char *argv[])
{
srand(time(0));
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_t id1,id2;
pthread_create(&id1,0,run1,0);
pthread_create(&id2,0,run2,0);
pthread_join(id1,0);
pthread_join(id2,0);
return 0;
}
第三题:创建2个线程,一个线程负责向文件中写入数据,一个线程负责从文件中读取数据并输出
pthread_mutex_t m1;
pthread_mutex_t m2;
void* run1(void* arg)
{
while(1){
pthread_mutex_lock(&m1);
FILE* wfp=fopen("./1.c","w");
char buf[64]={0};
printf("please enter:");
scanf("%s",buf);
while(getchar()!=10);
fwrite(buf,64,1,wfp);
fclose(wfp);
pthread_mutex_unlock(&m2);
}
}
void* run2(void* arg)
{
while(1){
pthread_mutex_lock(&m2);
FILE* rfp=fopen("./1.c","r");
char buf[64]={0};
fread(buf,64,1,rfp);
printf("read=%s\n",buf);
fclose(rfp);
pthread_mutex_unlock(&m1);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_mutex_lock(&m2);
pthread_t id1,id2;
pthread_create(&id1,0,run1,0);
pthread_create(&id2,0,run2,0);
pthread_join(id1,0);
pthread_join(id2,0);
return 0;
}
思维导图