在pthreads标准库里面, 库本身并不提供对信号量的支持,因为POSIX标准并没有对信号量做出定义,但是如果你一定要使用信号量来完成程序的话,那么所有的内容都会包含在semphore.h文件里
请注意:不要混合着使用系统V自带的信号量,系统V的信号量位于sys/sem.h文件中
1
#include <semaphore.h>
2
#include <pthread.h>
3
#include <stdio.h>
4
#define THREADS 20
5
sem_t OKToBuyMilk;
6
int milkAvailable;
7
void* buyer(void *arg)
8

{
9
//P()
10
sem_wait(&OKToBuyMilk);
11
if(!milkAvailable)
12
{
13
//Buy Some Milk
14
++milkAvailable;
15
}
16
//V()
17
sem_post(&OKToBuyMilk);
18
return;
19
}
20
int main(int argc, char* argv[])
21

{
22
int i;
23
pthread_t threads[THREADS];
24
milkAvailable=0;
25
//initlization the semphore with a value of 1.
26
//Note the second argument: passing zero denotes
27
//that the semaphore is shared between threads (and
28
//not processes)
29
if(sem_init(&OKToBuyMilk,0,1))
30
{
31
printf("Could not initialization a semphore\n");
32
return -1;
33
}
34
for(i=0;i<THREADS; ++i)
35
{
36
if(pthread_create(&threads[i],NULL,&buyer,NULL))
37
{
38
printf("Could not create thread %d\n",i);
39
return -1;
40
}
41
}
42
for(i=0;i<THREADS; ++i)
43
{
44
if(pthread_join(threads[i],NULL))
45
{
46
printf("Could not join thread %d\n",i);
47
return -1;
48
}
49
}
50
sem_destroy(&OKToBuyMilk);
51
//Make sure we don't have too much milk,
52
printf("Total milk: %d\n", milkAvailable);
53
return 0;
54
}
55
运行程序

关于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
posted on 2010-10-02 23:54
sohu2000000 阅读(1237)
评论(2) 编辑 收藏 引用