无法在我的多线程程序中找到错误?

时间:2016-05-25 05:29:45

标签: c multithreading mutex

我已经实现了一个简单的多线程程序,生成器访问全局变量并填充它,然后由消费者打印出来。

我写过这样的主要内容

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

void *prod(void);
void *cons(void);

unsigned int my_var = 0;

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{
    pthread_t th1, th2;
    int status;

    status = pthread_create(&th1, NULL, (void*)prod, NULL);
    if(status)
    {
        printf("Error creating thread 1 : %d\n", status);
        exit(-1);
    }
    status = pthread_create(&th2, NULL, (void*)cons, NULL);
    if(status)
    {
         printf("Error creating thread 2 : %d\n", status);
         exit(-1);
    }

    pthread_join(th1, NULL);
    pthread_join(th2, NULL);

    return 0;
}

我的制作人功能是这样的:

void *prod(void)
{
    while(1)
    {
        pthread_mutex_unlock(&mut);
        printf("Enter the value : ");
        scanf("%d", &my_var);
    }
}

消费者功能是:

void *cons(void)
{
    while(1)
    {
        printf("The value entered was %d\n", my_var);
        pthread_mutex_lock(&mut);
    }
}

此程序以精确输出运行,但模式不同,如:

Enter the value : The value entered was 0
The value entered was 0
45
Enter the value : The value entered was 45
85
Enter the value : The value entered was 85
12
Enter the value : The value entered was 12
67
Enter the value : The value entered was 67
49
Enter the value : The value entered was 49

我发现很难纠正这种逻辑,因为它是线程概念的新手。 请帮我解决这个问题。

我的预期输出:

Enter the value : 45
The value entered is 45
.........................................

在使用mutex_cond_var之后的一些答案和指南。我在这样的函数中使用它们:

void *prod(void)
{
    while(1)
    {
        printf("Enter the value : ");
        scanf("%d", &my_var);
        pthread_cond_signal(&condition_var1);
        pthread_mutex_unlock(&mut);
    }  
}

void *cons(void)
{
    while(1)
    {
        pthread_mutex_lock(&mut);
        pthread_cond_wait( &condition_var1, &mut );
        printf("The value entered was %d\n", my_var);
    }
}

结果输出:

Enter the value : 78
Enter the value : The value entered was 78
86
Enter the value : 15
Enter the value : The value entered was 15
35
Enter the value : 86
Enter the value : The value entered was 86
12
Enter the value : 65
Enter the value : The value entered was 65
78
Enter the value : 65
Enter the value : The value entered was 65
12
Enter the value : 35
Enter the value : The value entered was 35

请指导我清理代码以获得预期的输出。

2 个答案:

答案 0 :(得分:1)

逻辑上,Producer代码可能会在Consumer有机会运行之前运行多次。在这种情况下,您可能会错过一些输入的值。您需要2个互斥锁。 mutex_fullmutex_empty

初始值:mutex_full = NON_SIGNALEDmutex_empty = SIGNALED

Producer()
{
Wait(mutex_empty);
//produce code
Signal(mutex_full);
}

Consumer()
{
Wait(mutex_full);
//consumer code
Signal(mutex_empty);
}

答案 1 :(得分:0)

我建议在这种情况下使用条件变量。

https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview

这种方式对您的任务更有效。所以消费者应该等待一些cond变量。当生产者获得新数据时,他将通知条件变量,消费者将醒来对该数据做一些工作。

上面的链接有很好的解释,但如果您有疑问,欢迎您