一、关于信号量机制解决进程同步问题:
1、整型信号量;
2、记录型信号量:采用记录型数据结构(资源数目,在等待该资源的进程链表);能够实现让权等待(if(S.value<0) block(S.L));
3、AND 型信号量:一次申请若干种资源,每种资源仅申请一个(从能够申请的资源种类上时行扩充);
4、信号量集:一次申请若干种资源,每种资源可申请若干个,并且可控制资源分配下限。
二、用记录型信号量解决生产者--消费者问题
semaphore mutem=1;
semaphore empty=n;
semaphore full=0;
item array[n];
int in=0;
int out=0;
producer()
{
while(ture)
{
produce an item in next_product;
waite(empty);
waite(mutex);
array[in]=next_product;
in=(in+1)%n;
signal(mutex);
signal(full);
}
}
consumer()
{
while(ture)
{
waite(full);
waite(mutex);
mext_consumer=array[out];
out=(out+1)%n;
signal(mutex);
signal(empty);
}
}
三、用AND 型信号量解决生产者--消费者问题
semaphore mutex=1;
semaphore empty=n;
semaphore full=0;
item array[n];
int in=0;
int out=0;
producer()
{
while(ture)
{
produce an item in next_product;
Swaite(empty,mutex);
array[in]=next_product;
in=(in+1)%n;
Ssignal(mutex,full);
}
}
consumer()
{
while(ture)
{
Swaite(full,mutex);
next_consumer=array[out];
out=(out+1)%n;
Ssignal(mutex,empty);
consum the product in next_consumer;
}
}
四、用记录型的信号量和信号量集结合使用来解决生产者--消费者问题(这里,每个生产者一次生产 m 个产品放入缓冲区,每个消费者一次取一个产品)
semaphore mutex=1;
semaphore empty=n;
semaphore full=0;
item array[n];
int in=0;
int out=0;
int m=3;
int next_product[m];
producer()
{
while(ture)
{
produce_m_products();
Swaite(empty,m,m; mutex);
put_m_products();
Ssignal(full,m; mutex);
}
}
consumer()
{
while(ture)
{
Swaite(full,mutex);
next_consumer=array[out];
out=(out+1)%n;
Signal(mutex,empty);
consuming....;
}
}
produce_m_products()
{
int i;
while(i=0;i<m;i++)
produce an item in next_producct[i];
}
put_m_product()
{
int i;
for(i=0;i<m;i++)
{
array[in]=next_product[i];
in=(in+1)%n;
}
}