作业:
第一题:
pthread_mutex_t m1;
pthread_mutex_t m2;
void *task2(void *arg){
pthread_mutex_lock(&m2);
int fd1=open("./work.txt",O_RDONLY);
char buf[64]={0};
int res=read(fd1,buf,30);
printf("%s\n",buf);
//memset(buf,0,sizeof(buf));
close(fd1);
pthread_mutex_unlock(&m1);
}
int main(int argc, const char *argv[])
{
pthread_t id2;
pthread_create(&id2,0,task2,0);
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_mutex_lock(&m2);
pthread_mutex_lock(&m1);
int fd=open("./work.txt",O_WRONLY|O_CREAT|O_TRUNC,0664);
char str[64]="helloworldilovechinaicandomoreicandobetter";
write(fd,str,30);
close(fd);
pthread_mutex_unlock(&m2);
pthread_join(id2,0);
return 0;
}
第二题:
pthread_mutex_t m,m1,m2,m3,m4;
void *task(void *arg){
while(1){
pthread_mutex_lock(&m1);
printf("2\n");
sleep(1);
pthread_mutex_unlock(&m2);
}
}
void *task1(void *arg){
while(1){
pthread_mutex_lock(&m2);
printf("3\n");
sleep(1);
pthread_mutex_unlock(&m3);
}
}
void *task2(void *arg){
while(1){
pthread_mutex_lock(&m3);
printf("4\n");
sleep(1);
pthread_mutex_unlock(&m4);
}
}
void *task3(void *arg){
while(1){
pthread_mutex_lock(&m4);
printf("5\n");
sleep(1);
pthread_mutex_unlock(&m);
}
}
int main(int argc, const char *argv[])
{
pthread_t id,id1,id2,id3;
pthread_mutex_init(&m,0);
pthread_mutex_init(&m1,0);
pthread_mutex_lock(&m1);
pthread_mutex_init(&m2,0);
pthread_mutex_lock(&m2);
pthread_mutex_init(&m3,0);
pthread_mutex_lock(&m3);
pthread_mutex_init(&m4,0);
pthread_mutex_lock(&m4);
pthread_create(&id,0,task,0);
pthread_create(&id1,0,task1,0);
pthread_create(&id2,0,task2,0);
pthread_create(&id3,0,task3,0);
pthread_detach(id);
pthread_detach(id1);
pthread_detach(id2);
pthread_detach(id3);
while(1){
pthread_mutex_lock(&m);
printf("1\n");
sleep(1);
pthread_mutex_unlock(&m1);
}
return 0;
}
思维导图: