【原创】跟刘峰六学C语言(3) 信号量
时间:2010-10-02 来源:sohu2000000
跟刘峰六学C语言(3) 信号量 收藏
在pthreads标准库里面, 库本身并不提供对信号量的支持,因为POSIX标准并没有对信号量做出定义,但是如果你一定要使用信号量来完成程序的话,那么所有的内容都会包含在semphore.h文件里
请注意:不要混合着使用系统V自带的信号量,系统V的信号量位于sys/sem.h文件中
- #include <semaphore.h>
- #include <pthread.h>
- #include <stdio.h>
- #define THREADS 20
- sem_t OKToBuyMilk;
- int milkAvailable;
- void* buyer(void *arg)
- {
- //P()
- sem_wait(&OKToBuyMilk);
- if(!milkAvailable)
- {
- //Buy Some Milk
- ++milkAvailable;
- }
- //V()
- sem_post(&OKToBuyMilk);
- return;
- }
- int main(int argc, char* argv[])
- {
- int i;
- pthread_t threads[THREADS];
- milkAvailable=0;
- //initlization the semphore with a value of 1.
- //Note the second argument: passing zero denotes
- //that the semaphore is shared between threads (and
- //not processes)
- if(sem_init(&OKToBuyMilk,0,1))
- {
- printf("Could not initialization a semphore\n");
- return -1;
- }
- for(i=0;i<THREADS; ++i)
- {
- if(pthread_create(&threads[i],NULL,&buyer,NULL))
- {
- printf("Could not create thread %d\n",i);
- return -1;
- }
- }
- for(i=0;i<THREADS; ++i)
- {
- if(pthread_join(threads[i],NULL))
- {
- printf("Could not join thread %d\n",i);
- return -1;
- }
- }
- sem_destroy(&OKToBuyMilk);
- //Make sure we don't have too much milk,
- printf("Total milk: %d\n", milkAvailable);
- return 0;
- }
运行程序
[support@smtp2 ailf]$ gcc semaphore.c -o semaphore -lpthread
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$ ./semaphore
Total milk: 1
[support@smtp2 ailf]$
关于Semphore的API有下面几点说明:
- sem_init: 初始化一个新的semphore变量,第二个参数指出信号量的共享方式,0意味着该信号量是在线程间共享的而不是在进程间共享,最后的一个参数说明了信号量初始化时候的初始值
- sem_destroy: 析构掉一个已经退出的semphore变量
- sem_wait: 相当于P()操作
- sem_post: 相当于V()操作
下面让我们用表格的形式总结一下关于线程操作的一些方法
基本操作 | 绝缘量 | 互斥量 | 信号量 | |
生成 | pthread_create | pthread_barrier_init | pthread_mutex_init | sem_init |
析构 | pthread_exit | pthread_barrier_destroy | pthread_mutex_destroy | sem_destroy |
挂起等待 | pthread_join | pthread_barrier_wait | --- | --- |
获得资源 | --- | --- | pthread_mutex_lock | sem_wait |
释放 | --- | --- | pthread_mutex_unlock | sem_post |
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/asiainfolf/archive/2010/10/02/5918625.aspx