【问题标题】:pthread and accessing the critical sectionpthread 和访问临界区
【发布时间】:2015-11-15 03:18:41
【问题描述】:

好吧,下面的代码是针对两个线程的。我对互斥锁有一些问题。 创建线程 t1 后,它调用 add_queue()。然后它会通知线程 t2 在其临界区工作。但是,该程序不会为线程 t2 运行。 线程 t1 运行并在其临界区完成工作。然后,我锁定了线程 t2 的互斥锁。但是,程序卡在第 29 行。

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

static int pending_requests =0;
static pthread_mutex_t prmutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t prcondition = PTHREAD_COND_INITIALIZER;

static int critical = 0;

int get_number_requests(void)
{
    return pending_requests;
}

void add_queue()
{
    pthread_mutex_lock(&prmutex);
    pending_requests++;
    critical++;    
    pthread_mutex_unlock(&prmutex);
    printf("xxxx\n");
    printf("critical=%d\n",critical);

}

void remove_from_queue()
{
    pthread_mutex_lock(&prmutex);
    pending_requests--;
    printf("BBBBcritical=%d\n",critical);
    critical--;
    printf("BBBcritical=%d\n",critical);

    pthread_mutex_unlock(&prmutex);

}

void *get_request()
{
    add_queue();
    if (get_number_requests() != 0)
    {    
        printf("I have a element in the queue. Signalling to processor thread..\n");
        pthread_cond_signal(&prcondition);
    }
    pthread_exit(0);
}

void *processor()
{
    while(get_number_requests() == 0)
    {
        printf("BBB This is a processor thread, I am waiting..\n");
        pthread_cond_wait(&prcondition,&prmutex);
    }
    while(get_number_requests() !=0)
    {
        printf("aaaa\n");
        remove_from_queue();
        pthread_cond_signal(&prcondition);
    }

    pthread_exit(0);
}


int main()
{
    pthread_t t1,t2;
    printf("critical=%d\n",critical);
    pthread_create(&t1,NULL,get_request,NULL);
    pthread_create(&t2,NULL,processor,NULL);
    printf("critical=%d\n",critical);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
}

【问题讨论】:

    标签: linux operating-system pthreads


    【解决方案1】:

    您对pthread_cond_wait 的使用在很多方面都是错误的。仔细阅读man page for pthread_cond_wait 将帮助您了解如何正确使用它。

    1. 在调用pthread_cond_wait 之前,必须锁定互斥锁。来自手册:

      它们应该被调用线程锁定的互斥锁调用,或者 未定义的行为结果。

      也就是说,你需要在调用pthread_cond_wait之前调用pthread_mutex_lock

    2. pthread_cond_wait 返回时,它将锁定互斥锁。来自手册:

      成功返回后,互斥体应已被锁定并归调用线程所有。

      因此在remove_from_queue 中再次尝试锁定它是错误的。由于互斥体已被锁定,remove_from_queue 中的 pthread_mutex_lock 调用将在您发现时无限期地阻塞(即线程本身已死锁)。

    【讨论】:

    • 谢谢,我会看到的。
    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多