confide

导航

unix编程——互斥锁

互斥锁用于保护临界区,保证任何时刻只有一个线程或进程执行其中的代码,临界区是一次只能允许一个线程或进程使用的共享资源。

生产者和消费者问题

代码如下:

View Code
#include <stdlib.h>
#include
<stdio.h>
#include
<pthread.h>

int nitems;
pthread_mutex_t imux;
int curp;

void*producer()
{
while(1){
pthread_mutex_lock(
&imux);
curp
++;
if(curp>nitems){
pthread_mutex_unlock(
&imux);
return0;
}
printf(
"p %d\n",curp);

pthread_mutex_unlock(
&imux);
sleep(
1);
}

}
void*consumer()
{
int i;
for(i=1;i<=nitems;i++){
while(1){
pthread_mutex_lock(
&imux);
if(i<curp){
pthread_mutex_unlock(
&imux);
break;
}
pthread_mutex_unlock(
&imux);
}
printf(
"c %d\n",i);
}

}
int main()
{
pthread_t th_prod;
pthread_t th_cosm;
int i,j;
nitems
=10;
pthread_setconcurrency(
2);
pthread_create(
&th_prod,NULL,producer,NULL);
pthread_create(
&th_cosm,NULL,consumer,NULL);
pthread_join(th_prod,NULL);
pthread_join(th_cosm,NULL);
exit(
0);
}

输出:

View Code
p 1
p
2
c
1
p
3
c
2
p
4
c
3
p
5
c
4
p
6
c
5
p
7
c
6
p
8
c
7
p
9
c
8
p
10
c
9
c
10

应该注意的是:

1、sleep(1)要在释放了锁后面,要么就没有效果。

2、pthread_setconcurrency(2)为设置并发数,但是当注释掉时,结果无变化,还有待深究。。。

3、当消费者得不到要消费的数字时,会一直等到下去,浪费了cpu资源。为条件变量做铺垫。

posted on 2011-08-10 10:32  confide  阅读(335)  评论(0)    收藏  举报