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

Not able to find the bug in my multithreading program?

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

主线我是这样写的

#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 个互斥量。 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);
}

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

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

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

上面的link解释的还不错,有问题欢迎留言