生产环境死锁java_生产环境 者 - 消费者队列中的奇怪死锁

使用C的pthread库,我正在尝试实现一个简单的 生产环境 者 - 消费者模式 .

生产环境 者生成随机数并将它们放入这样的队列中

typedef struct {

int q[MAX_QUEUE];

int head;

int tail;

} queue;

消费者只需逐个获取数字并将其打印到标准输出 . 使用一个 mutex 和两个条件变量完成同步: empty_queue (如果队列为空则暂停使用者)和 full_queue (如果队列已满,则暂停 生产环境 者) . 问题是两个线程在到达生成/消耗的元素时都会挂起,因此它们会进入死锁状态 . 我想我做的一切都是正确的,我可以做错了 .

制片人:

void* producer(void* args) {

unsigned seed = time(NULL);

int random;

queue *coda = (queue *) args;

while(1) {

Pthread_mutex_lock(&queue_lock);

while(coda->head == MAX_QUEUE-1) { // Full Queue

printf("Suspending producer\n");

fflush(stdout);

Pthread_cond_wait(&full_queue, &queue_lock);

}

random = rand_r(&seed) % 21;

enqueue(coda, random);

Pthread_cond_signal(&empty_queue);

Pthread_mutex_unlock(&queue_lock);

sleep(1);

}

return NULL;

}

消费者:

void* consumer(void* args) {

queue *coda = (queue *) args;

int elem;

while(1) {

Pthread_mutex_lock(&queue_lock);

while(coda->head == coda->tail) { // Empty Queue

printf("Suspending Consumer\n");

fflush(stdout);

Pthread_cond_wait(&empty_queue, &queue_lock);

}

elem = dequeue(coda);

printf("Found %i\n",elem);

Pthread_cond_signal(&full_queue);

Pthread_mutex_unlock(&queue_lock);

}

return NULL;

}

入队/出队例程

static void enqueue(queue *q, int elem) {

q->q[(q->tail)] = elem;

(q->tail)++;

if(q->tail == MAX_QUEUE)

q->tail = 0;

}

static int dequeue(queue *q) {

int elem = q->q[(q->head)];

(q->head)++;

if(q->head == MAX_QUEUE)

q->head = 0;

return elem;

}

Pthread_ *只是标准pthread_ *库函数的包装函数 . 输出(MAX_QUEUE = 10):

Suspending Consumer

Found 16

Suspending Consumer

Found 7

Suspending Consumer

Found 5

Suspending Consumer

Found 6

Suspending Consumer

Found 17

Suspending Consumer

Found 1

Suspending Consumer

Found 12

Suspending Consumer

Found 14

Suspending Consumer

Found 11

Suspending Consumer

Suspending producer

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值