【发布时间】:2017-09-30 14:37:33
【问题描述】:
我们研究过,如果我们处理多线程问题,那么我们使用一种称为互斥锁的线程同步方法,它允许锁定临界区,以便其他线程不会干扰并进入阻塞状态,直到互斥锁解锁临界区。
但是我在我的程序中做这件事,但是这个程序的输出与互斥锁的概念不匹配。如果我错了,请纠正我。
代码
#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做了什么。 -
它将通过使用来自其他进程或线程的信号等待某个条件变为真。
-
锁定一个互斥锁 inside 一个循环并相应解锁 outside 循环通常是一个坏主意——在你的
consumer()函数中,如果while(i<MAX)循环体重复,您将尝试在the_mutex已锁定时锁定它(您不应该这样做)。 -
错误地将其放入循环中。
-
@suleman 这是全部吗? (提示:否)
标签: c multithreading operating-system pthreads mutex