Mutex 已锁定,但其他线程正在进入临界区

Mutex is lock but other threads are entering in critical section

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

但是我在我的程序中做这件事但是这个程序的输出与互斥量的概念不匹配。如果我错了,请纠正我。

代码

#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 returns 再次持有互斥体上的锁。检测到队列非空,可以进入出队临界区。