#include <stdio.h>
#include <semaphore.h>
#include <strings.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
char buf[30];
sem_t sem; // 定义信号量
void *con_do(void *arg){
while(1){
sem_wait(&sem); // p操作
printf("I am thread,buf=[%s]\n",buf);
bzero( buf, 30);
}
}
int main(){
// 1.初始化信号量,并判断是否成功
if( sem_init( &sem, 0, 0) == -1 ){
fprintf( stdout, "sem_init error,errno=%d,%s",
errno, strerror(errno));
return 1;
}
// 2.创建一个子线程,并用于打印主线程输入的字符串
pthread_t pid;
pthread_create( &pid, NULL, con_do, NULL);
// 3.输入字符串
while(1){
scanf("%s",buf);
sem_post(&sem); // v操作
}
return 0;
}