sem_wait 和 sem_post这两个函数经常在线程同步时使用,伴随的还有创建和销毁函数sem_init,sem_destroy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
static sem_t sem_t1;
static int status = 1;
static pthread_t pthread_t1 = -1;
static pthread_t pthread_t2 = -1;
void *f1(void)
{
while(status)
{
sem_wait(&sem_t1); //阻塞,等待sem_post发信号唤醒
printf("hello world.\n");
}
printf("bye bye.\n");
pthread_exit(NULL);
}
void *f2(void)
{
char buf[128] = {0};
while(1)
{
scanf("%s", buf);
printf("you input is:%s\n", buf);
if(!strcmp("0", buf))
{
status = 0;
sem_post(&sem_t1); //唤醒sem_wait,推出程序
break;
}
memset(buf, 0, sizeof(buf)); //唤醒sem_wait
sem_post(&sem_t1);
}
pthread_exit(NULL);
}
void create(void)
{
int ret = -1;
ret = sem_init(&sem_t1, 0 , 0); //初始化信号量
if(ret)
{
printf("sem_init error ret=%d\n", ret);
return;
}
ret = pthread_create(&pthread_t1, NULL, (void*)f1, NULL);
if(ret)
{
printf("pthread_create t1 ret=%d\n", ret);
return;
}
ret = pthread_create(&pthread_t2, NULL, (void*)f2, NULL);
if(ret)
{
printf("pthread_create t2 ret=%d\n", ret);
}
}
void destroy(void)
{
printf("waiting thread exit.\n");
if(pthread_join(pthread_t1, NULL) || pthread_join(pthread_t2, NULL))
{
perror("pthread_join");
}
sem_destroy(&sem_t1); //销毁信号量
}
int main(int argc, char const *argv[])
{
create();
destroy();
return 0;
}