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资源。为条件变量做铺垫。

转载于:https://www.cnblogs.com/confide/archive/2011/08/10/2132133.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值