线程信号量同步

来源

https://blog.csdn.net/yishizuofei/article/details/78213108

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#include <semaphore.h>


char buf[128] = {0};
sem_t sem;

void *fun_pthread1(void *arg)
{
while(1)
{
sem_wait(&sem);
if(strncmp(buf,"end",3)==0)
{
break;
}
int count=0;
while(1)
{
if(buf[count]==0 || buf[count] == ' ')
{
break;
}
count++;
}
printf("count:%d ",count);
sem_post(&sem);
sleep(1);
}
}


int main()
{
sem_init(&sem,5,1);
sem_wait(&sem);
pthread_t id;
pthread_create(&id,NULL,fun_pthread1,NULL);
while(1)
{
printf("please input ");
fgets(buf,128,stdin);
sem_post(&sem);
if(strncmp(buf,"end",3)==0)
{
break;
}
sleep(1);
sem_wait(&sem);
}

pthread_join(id,NULL);
sem_destroy(&sem);
pthread_exit(NULL);
return 0;
}

原文地址:https://www.cnblogs.com/zhangjianrong/p/10477738.html