互斥线程 - 代码似乎没有正确退出

时间:2015-02-18 18:53:37

标签: c multithreading mutex

所以我这里有代码,它有两种线程。一种"生产"数据和另一个消费"它。任何时候都只能存在一定数量的数据,因此一旦创建了一定数量的数据(即,当sharedData = BUFFER时),生产者将暂停生成,并且当sharedData = 0时,消费者将暂停还有很多数据可以制作(数量存储在dataleft中),一旦制作和使用了所有数据,程序就应该结束了。

出于某种原因,我在代码末尾的printf()行似乎永远不会触发。因此,我无法判断线程是否正确关闭。感觉我做了一些非常愚蠢的事情,但我无法看到这个问题。

一开始就有几个定义:

#define                 NUMCONSUMERS    4
#define                 NUMPRODUCERS    4
#define                 PACKETS         10
#define                 tryMainlock     pthread_mutex_trylock(&dataMutex)
#define                 openMainlock    pthread_mutex_lock(&dataMutex)
#define                 closeMainlock   pthread_mutex_unlock(&dataMutex)
#define                 waitMainlock    pthread_cond_wait(&dataPresentCondition, &dataMutex);
#define                 signalMainlock  pthread_cond_signal(&dataPresentCondition);

#define                 trydatalock     pthread_mutex_trylock(&IsthereDataleft)
#define                 opendatalock    pthread_mutex_lock(&IsthereDataleft)
#define                 closedatalock   pthread_mutex_unlock(&IsthereDataleft)

pthread_mutex_t         dataMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t          dataPresentCondition = PTHREAD_COND_INITIALIZER;

pthread_mutex_t         IsthereDataleft = PTHREAD_MUTEX_INITIALIZER;

int                     sharedData=0;   //amount of data present
int                     BUFFER = 5;
int                     dataleft=PACKETS;

主要功能:

int main(int argc, char **argv)
{
int rc;                                 
int i;
pthread_t  consumer[NUMCONSUMERS];
pthread_t  producer[NUMPRODUCERS];

rc = opendatalock;                      //lock to determine whether there's any point waiting for data

for (i=0; i <NUMPRODUCERS; i++) {       //Build up the producers
    rc = pthread_create(&producer[i], NULL, Producer, (void *)i);
    if (rc)
        printf("Error building Producer Thread: %x\n", i);
}

for (i=0; i <NUMCONSUMERS; i++) {       //Build up the consumers
    rc = pthread_create(&consumer[i], NULL, Consumer, (void *)i);
    if (rc)
        printf("Error building Consumer Thread: %x\n", i);
}

printf("All Producers and Consumers created\n");

for (i=0; i <NUMPRODUCERS; i++) {       //Join up the producers
    rc = pthread_join(producer[i], NULL);
    if (rc)
        printf("Error: Producer %x: Failed to join\n", i);
}

rc = closedatalock;                     //producers finished, no data left to make

printf("datalock closed, consumers finishing...\n");
for (i=0; i <NUMCONSUMERS; i++) {       //Join up the consumers
    rc = pthread_join(consumer[i], NULL);
    if (rc)
        printf("Error: Consumer %x: Failed to join\n", i);
}
rc = pthread_mutex_destroy(&dataMutex);
rc = pthread_cond_destroy(&dataPresentCondition);
rc = pthread_mutex_destroy(&IsthereDataleft);

printf("All Threads finished. Exiting....\n");
return 0;
}

消费者线程:

void *Consumer(void *threadid){
int rc;
printf("Consumer Thread %x: Created\n", (int)threadid);
while (1)
{
    printf("Consumer %x: Entering Loop\n", (int)threadid);
    rc = openMainlock;      //take hold of main lock
    if (rc)
    {
        printf("Consumer %x: Waiting...\n", (int)threadid);
        rc = waitMainlock;  //if main lock is taken, wait
        if (rc)             //if wait fails, exit the thread.
        {
            printf("Consumer Thread %x: wait for Main Lock failed\n", threadid);
            exit(0);
        }
    }

    while (sharedData == 0) //if the buffer is empty
    {
        rc = trydatalock;
        if (!rc)
        {
            printf("Consumer %x: Completed. Exiting...\n");
            exit(0);
        }
        rc = closeMainlock;
        if (rc)
        {
            printf("code.\n");
        }
        rc = waitMainlock;
        if (rc)
        {
            printf("code.\n");
        }
    }
    sharedData--;
    rc = closeMainlock;
    rc = signalMainlock;
    if (rc)
        {
            printf("code.\n");
        }
    printf("Consumer %x: Releasing Lock\n", (int)threadid);         
}
}

制片人主题:

void *Producer(void *threadid){
int rc;
printf("Producer Thread %x: Created\n", (int)threadid);
while (1)
{
    printf("Producer %x: Entering Loop\n", (int)threadid);
    rc = openMainlock;          //take hold of the lock
    if (rc)                     //if lock is currently being used by a consumer or a producer
    {   
        printf("Producer %x: Waiting...\n", (int)threadid);
        rc = waitMainlock;      //wait here until lock is released
        if (rc)
        {
            printf("Producer Thread %x: wait for Main Lock failed\n", threadid);
            exit(0);
        }
    }
    if (!dataleft)              //If there's no data left to add to the stream, close the thread
    {
        printf("Producer Thread %x: Completed, exiting...\n", (int)threadid);
        exit(0);
    }
    while (sharedData >=BUFFER)
    {
        rc = closeMainlock;
        if (rc)
        {
            printf("code.\n");
        }
        rc = waitMainlock;
        if (rc)
        {
            printf("code.\n");
        }
    }
    printf("Producer %x: Lock Acquired\n", (int)threadid);
    sharedData++;
    dataleft--;
    rc = closeMainlock;
    rc = signalMainlock;
    if (rc)
        {
            printf("code.\n");
        }
    printf("Producer %x: Releasing Lock\n", (int)threadid);
}
}

2 个答案:

答案 0 :(得分:0)

使用openMainlock后,某些内容似乎出现了问题,扩展为pthread_mutex_lock来电。

一方面,您不应期望从openMainlock获得非零返回值:pthread_mutex_lock应该返回零(锁定获取)或阻止,除非互斥锁是未初始化或是错误检查互斥。

此外,一旦获得了锁,如果生成器完成,即dataleft为零,则线程调用exit(0),这将终止整个进程而不是终止线程。应该使用pthread_exit,或者只是从函数返回,但请注意,此时您仍然拥有主锁,但不会被释放。

答案 1 :(得分:0)

查看这段代码:

    if (!rc)
    {
        printf("Consumer %x: Completed. Exiting...\n");
        exit(0);
    }

如果消费者已完成,则终止进程(!)。您需要使用pthread_exit(),或者只是从线程函数返回。

然后,还有

../nptl/pthread_mutex_lock.c:80:
    __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.

我有几次运行代码。这可能是由例如双重解锁或其他一些无效使用。我开始清理奇怪的宏,这样你就可以自由地查看程序本身的逻辑。

另外,关于互斥锁的一个重要建议是:始终准确记录互斥锁应保护哪些数据。关键在于它并不总是清晰,并且错误意味着您在没有同步的情况下意外访问数据。为了使这一点非常清楚,请使用类似这样的结构:

 struct {
     pthread_mutex_t mutex;
     pthread_cond_t cond;
     int data;
 } synced_data = {
     PTHREAD_MUTEX_INITIALIZER,
     PTHREAD_COND_INITIALIZER,
     0
 };

实际上,文档重要的不仅仅是共享数据。例如IsthereDataleft:这是一个互斥锁,但它不会保护任何东西,对吧?相反,它用于向启动的线程发出信号,表示没有什么可做的,对吗?记录这不仅可以帮助其他人理解您的代码,还可以确保您了解自己的意图。有时,在尝试解释它时,你会发现自己有些事情没有意义。