作业要求:实现信号同步
运行代码:
#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>
sem_t sem,sem1;
void *function(void*arg){
while(1){
sem_wait(&sem1);
printf("function\n");
sleep(1);
sem_post(&sem);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t a_thread;
//信号初始化
if(sem_init(&sem,0,1)<0){
perror("sem_init");
exit(-1);
}
if(sem_init(&sem1,0,1)<0){
perror("sem1_init");
exit(-1);
}
if(pthread_create(&a_thread,NULL,function,NULL)!=0){
printf("线程创建失败\n");
exit(-1);
}
while(1){
sem_wait(&sem);
printf("main\n");
sleep(1);
sem_post(&sem1);
}
sem_destroy(&sem);
sem_destroy(&sem1);
return 0;
}
运行截图: