信号量不是信号。
信号量的使用:
头文件 <semaphore.h>
定义信号量 sem_t sem;
初始化 sem_init(&sem);
等待信号量 sem_wait(&sem);
发送信号量 sem_post(&sem);
销毁信号量 sem_destroy(&sem);
/*requirment: pthread0 prints string before pthread1
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t mutex;
sem_t sem;
int source=10;
void pthread0(void)
{
while(1)
{
pthread_mutex_lock(&mutex);
source=0;
pthread_mutex_unlock(&mutex);
printf("this is thread0 and the source is %d\n",source);
sem_post(&sem);
sleep(2);
}
}
void pthread1(void)
{
while(1)
{
sem_wait(&sem);
pthread_mutex_lock(&mutex);
source=1;
pthread_mutex_unlock(&mutex);
printf("this is thread1 and the source is %d\n",source);
sleep(2);
}
}
void main()
{
pthread_t id0;
pthread_t id1;
sem_init(&sem,0,0);
pthread_mutex_init(&mutex,NULL);
pthread_create(&id0,NULL,(void*)pthread0,NULL);
pthread_create(&id1,NULL,(void*)pthread1,NULL);
while(1)
{
printf("this is main function\n");
sleep(2);
}
pthread_join(id0,NULL);
pthread_join(id1,NULL);
}