gpt4 book ai didi

c - 互斥锁已锁定,但其他线程正在进入临界区

转载 作者:行者123 更新时间:2023-12-04 21:50:52 25 4
gpt4 key购买 nike

我们研究过,如果我们处理多线程问题,那么我们使用一种称为互斥量的线程同步方法,它允许锁定关键部分,以便其他线程不会干扰并进入阻塞状态,直到互斥量解锁关键部分。

但是我在程序中执行此操作,但该程序的输出与互斥体的概念不匹配。如果我错了请纠正我。

代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>

#define MAX 10

pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int toConsume=0;
int i;

void* consumer(void *ptr) {
pthread_mutex_lock(&the_mutex);
while(i<MAX)
{
/* protect buffer */
while (toConsume <= 0) /* If there is nothing in the buffer then wait */
{
printf("Waiting Thread id:%lu \n",pthread_self());
pthread_cond_wait(&condc, &the_mutex);
}
pthread_mutex_unlock(&the_mutex); /* release the buffer */

sleep(2);

pthread_mutex_lock(&the_mutex); /* protect buffer */
toConsume--;
i++;
}
pthread_mutex_unlock(&the_mutex); /* release the buffer */
pthread_exit(0);
}

int main(int argc, char **argv) {
pthread_t pro, con[3];
pthread_mutex_init(&the_mutex, NULL);
pthread_cond_init(&condc, NULL); /* Initialize consumer condition variable */
pthread_cond_init(&condp, NULL); /* Initialize producer condition variable */

// Create the threads

for(int i=0 ;i<3;i++)
pthread_create(&con[i], NULL, consumer, NULL);

for(int i=0 ;i<3;i++)
pthread_join(con[i], NULL);

return 0;
}

输出

$ ./ex
Waiting Thread id:140580582618880
Waiting Thread id:140580574226176
Waiting Thread id:140580565833472

即使互斥锁保持锁定状态,所有线程都会进入临界区。

最佳答案

函数pthread_cond_wait将在线程等待时解锁所持有的互斥锁。这允许另一个线程进入临界区。

使用pthread_cond_wait的目的是线程需要等待某些条件变为真,然后才能真正执行临界区内的工作。要首先测试条件需要锁定互斥体。但是,如果条件为假,则必须等待某个事件使条件为真。如果它在持有锁的情况下等待,则其他线程将无法更新状态以使条件变为真,因为更新条件也需要锁定相同的互斥体。

因此,当等待条件变量时,互斥锁被解锁,以允许另一个线程获取锁来执行使条件成立的操作。

举个例子,考虑一个作业队列。线程将锁定互斥体以从队列中获取作业。但是,如果队列为空,则必须等待队列中出现作业。这是必须等待的条件,并且可以使用条件变量来实现该目的。当它对条件变量调用 pthread_cond_wait 时,关联的互斥体将被解锁。

另一个线程希望将作业放入队列中。该线程可以锁定互斥体,将作业添加到队列,向条件变量发出信号,然后解锁互斥体。

当条件变量发出信号时,等待线程被唤醒,pthread_cond_wait 返回并再次持有互斥锁上的锁。它检测到队列非空,可以进入将作业从队列中出列的临界区。

关于c - 互斥锁已锁定,但其他线程正在进入临界区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43748597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com