来源
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] == '\n')
{
break;
}
count++;
}
printf("count:%d\n",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\n");
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;
}