1. sem_init函数:sem是要初始化的信号量,pshared表示此信号量是在进程间共享还是线程间共享,value是信号量的初始值。
int sem_init(sem_t *sem, int pshared, unsigned int value);
2.sem_destroy函数:sem是要销毁的信号量。只有用sem_init初始化的信号量才能用sem_destroy销毁
int sem_destroy(sem_t *sem)
3.sem_wait函数:如果信号量的值为0,则线程阻塞,信号量的值大于0,将信号量的值减1,立即返回。成功返回0,失败返回-1。
int sem_wait(sem_t *sem)
4.sem_post函数:释放信号量,让信号量的值加1
int sem_post(sem_t *sem)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <windows.h>
sem_t sem;
static int i = 0;
void *thread1()
{
printf("thread_1 wait\n");
sem_wait(&sem);
printf("thread_1 continue run\n");
}
void *thread2()
{
for(i = 0; i < 10; i++)
{
printf("thread 2 count %d\n", i);
if(i == 5)
{
printf("thread 2 post\n");
sem_post(&sem);
usleep(10);
}
}
}
int main()
{
pthread_t tid1;
pthread_t tid2;
int ret1 = 0;
int ret2 = 0;
sem_init(&sem, 0, 0);
ret1 = pthread_create(&tid1, NULL, (void *)thread1, NULL);
if(ret1 < 0)
return -1;
usleep(5000);
ret2 = pthread_create(&tid2, NULL, (void *)thread2, NULL);
if(ret2 < 0)
return -1;
usleep(10000);
printf("end\n");
sem_destroy(&sem);
return 0;
}
结果:
thread_1 wait
thread 2 count 0
thread 2 count 1
thread 2 count 2
thread 2 count 3
thread 2 count 4
thread 2 count 5
thread 2 post
thread_1 continue run
thread 2 count 6
thread 2 count 7
thread 2 count 8
thread 2 count 9
end