互斥锁定 - 解锁生产者 - 消费者场景

时间:2016-02-08 05:31:33

标签: c multithreading pthreads mutex

我一直在阅读二进制信号量和互斥量之间的差异,并在链接mutex vs binary semaphore下面阅读它说" Mutex只能由获得它的线程发布,而你可以从任何其他线程(或进程)发出信号量信号,因此信号量更适合某些同步问题,如生产者 - 消费者"

但是在下面的示例中,我在一个线程中锁定互斥锁并在另一个线程中释放它。我是否误解了所提供链接中的陈述,或者我对自己的实现有错误的理解?再一次,我只是在探索代码以更好地理解事物,我并不期待事情能够发挥作用,但令我惊讶的是它工作得很好。

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

#define WORKERS 2
#define ARRAY_ELEMENTS 100
#define MAX 1000

pthread_mutex_t arraynotfull = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t access_array = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t arraynotempty = PTHREAD_MUTEX_INITIALIZER;

bool available = false;

void *worker_thread(void *pbucket)
{
    while(1)
    {
        unsigned int count = 0;
        int local_array[ARRAY_ELEMENTS];
        int *ptbucket = (int*)pbucket;
        setbuf(stdout, NULL);

        pthread_mutex_lock(&arraynotempty);
        pthread_mutex_lock(&access_array);
        while(count < ARRAY_ELEMENTS)
        {
            local_array[count] = ptbucket[count];
            count++;
        }
        pthread_mutex_unlock(&access_array);
        pthread_mutex_unlock(&arraynotfull);   //unlocking in consumer

        count = 0;

        while(count < ARRAY_ELEMENTS)
        {
            printf(" %d - \n", local_array[count]);
            count++;
        }
    }
}

int main(void)
{
    pthread_t thread_id[WORKERS];

    unsigned int* pbucket1 = (int*) malloc(sizeof(int) * ARRAY_ELEMENTS);

    unsigned int* pbucket = pbucket1;

    for(int i = 0; i < WORKERS - 1; i++)
    {
        pthread_create(&thread_id[i], NULL, worker_thread, (void *) pbucket);
    }

    for(int i = 0; i < MAX; i++)
    {
        unsigned int count = 0;

        // Make the payload ready
        pthread_mutex_lock(&arraynotfull);  // locking in producer
        pthread_mutex_lock(&access_array);
        while(count < ARRAY_ELEMENTS)
        {
            pbucket1[count] = i;
            i++;
            count++;
        }

        pthread_mutex_unlock(&access_array);
        pthread_mutex_unlock(&arraynotempty);
    }

    for(int i = 0; i < WORKERS; i++)
    {
        pthread_join(thread_id[i], NULL);
    }

    return 0;
}

0 个答案:

没有答案