/*
一个线程写,一个线程读,通过信号来实现同步
*/
#include"stdio.h"
#include"pthread.h"
#include"string.h"
#include"semaphore.h"
#define Success 0
#define Failure -1
char g_acBuf[128];
sem_t sem;
void *InputChar()
{
while(1)
{
printf("plean input array:\n");
gets(g_acBuf);
sem_post(&sem);
}
}
void *OutputLen()
{
int iNum;
while(1)
{
sem_wait(&sem);
iNum = strlen(g_acBuf);
printf("input array'len is %d\n",iNum);
}
}
int main()
{
int err;
pthread_t tid;
sem_init(&sem,0,0);
err=pthread_create(&tid,NULL,InputChar,NULL);
if(err=0)
printf("can’t create thread:%s\n",strerror(err));
err=pthread_create(&tid,NULL,OutputLen,NULL);
if(err=0)
printf("can’t create thread:%s\n",strerror(err));
sem_close(&sem);
sleep(10);
return Success;
}
转载于:https://my.oschina.net/sharelinux/blog/115381