/*主进程创建两个线程thread1和thread2,随后等待thread2的结束。
而thread2等待thread1给信号量加1从而停止阻塞,thread1又在等待
用户输入以往下执行。所以,程序运行的效果是:首先等待用户输入
字符,用户输入字符之后thread1输出字符串,并使信号量从0变为1,
然后thread1结束。thread2停止阻塞,输出字符串。最后主进程结束。*/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
struct sem_t
{
long int sem1;
};
struct sem_t sem; //define a struct of semaphore
void thread1()
{
int a;
a=getchar();
printf("This is the 1st thread !");
sem_post(&sem); //semaphore adds one
}
void thread2()
{
sem_wait(&sem); //block the present thread till semaphore is bigger than zero
printf("This is the 2nd thread !");
}
int main()
{
pthread_t t1,t2;
sem_init(&sem,0,0); //initialize semaphore
pthread_create(&t1,NULL,(void*)thread1,NULL); //create thread1
pthread_create(&t2,NULL,(void*)thread2,NULL); //create thread2
pthread_join(t2,NULL);
return 0;
}