#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
pthread_mutex_t ma;
pthread_mutex_t mb;
pthread_mutex_t mc;
pthread_mutex_t md;
pthread_mutex_t me;
void* task(void*arg)
{
while(1)
{
pthread_mutex_lock(&mb);
printf("2\n");
sleep(1);
pthread_mutex_unlock(&mc);
}
}
void* task2(void*arg)
{
while(1)
{
pthread_mutex_lock(&mc);
printf("3\n");
sleep(1);
pthread_mutex_unlock(&md);
}
}
void* task3(void*arg)
{
while(1)
{
pthread_mutex_lock(&md);
printf("4\n");
sleep(1);
pthread_mutex_unlock(&me);
}
}
void* task4(void*arg)
{
while(1)
{
pthread_mutex_lock(&me);
printf("5\n");
sleep(1);
pthread_mutex_unlock(&ma);
}
}
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mb,0);
pthread_mutex_lock(&mb);
pthread_mutex_init(&mc,0);
pthread_mutex_lock(&mc);
pthread_mutex_init(&md,0);
pthread_mutex_lock(&md);
pthread_mutex_init(&me,0);
pthread_mutex_lock(&me);
pthread_t id,id2,id3,id4,id5;
pthread_create(&id,0,task,0);
pthread_detach(id);
pthread_create(&id2,0,task2,0);
pthread_detach(id2);
pthread_create(&id3,0,task3,0);
pthread_detach(id3);
pthread_create(&id4,0,task4,0);
pthread_detach(id4);
while(1)
{
pthread_mutex_lock(&ma);
printf("1\n");
sleep(1);
pthread_mutex_unlock(&mb);
}
return 0;
}
Re.:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
pthread_mutex_t ma;
pthread_mutex_t mb;
void* task(void* arg)
{
pthread_mutex_lock(&mb);
int fd1=open("./1.txt",O_RDONLY);
while(1)
{
char brr[128]={0};
int res=read(fd1,brr,127);
if(res==0)
{
break;
}
printf("%s",brr);
}
close(fd1);
pthread_mutex_unlock(&ma);
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&ma,0);
pthread_mutex_init(&mb,0);
pthread_mutex_lock(&mb);
pthread_t id,id2;
pthread_create(&id,0,task,0);
// pthread_detach(id);
pthread_mutex_lock(&ma);
char arr[128]={0};
scanf("%s",arr);
int fd=open("./1.txt",O_WRONLY|O_TRUNC|O_CREAT,0666);
write(fd,arr,127);
close(fd);
pthread_mutex_unlock(&mb);
pthread_join(id,0);
return 0;
}
2024.8.9
最新推荐文章于 2024-10-03 20:40:32 发布