人类的孤独像是一种与生俱来的残疾。

互斥量与条件等待配合避免竞争

C语言 smallfish 1638℃
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

pthread_cond_t pthread_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t pthread_mutex = PTHREAD_MUTEX_INITIALIZER;

int goods = 0;

void *producer(void *arg)
{
    arg = arg;

    while(1){
        pthread_mutex_lock(&pthread_mutex);
        printf("[%s:%d]goods = %d\n", __func__, __LINE__, goods++);
        pthread_mutex_unlock(&pthread_mutex);
        pthread_cond_broadcast(&pthread_cond);
        sleep(2);
    }

    pthread_detach(pthread_self());
    pthread_exit(NULL);
}

void *costomer1(void *arg)
{
    arg = arg;

    printf("Hello, I'm %s!\n", __func__);
    while (1) {
        pthread_mutex_lock(&pthread_mutex);
        pthread_cond_wait(&pthread_cond, &pthread_mutex);
        printf("%s Get signal!\n", __func__);
        pthread_mutex_unlock(&pthread_mutex);
        if(goods > 20)break;
    }
    printf("[%s:%d]exit!\n", __func__, __LINE__);
    pthread_detach(pthread_self());
    pthread_exit(NULL);
}

void *costomer2(void *arg)
{
    arg = arg;

    printf("Hello, I'm %s!\n", __func__);
    while (1) {
        pthread_mutex_lock(&pthread_mutex);
        pthread_cond_wait(&pthread_cond, &pthread_mutex);
        printf("%s Get signal!\n", __func__);
        pthread_mutex_unlock(&pthread_mutex);
        if(goods > 20)break;
    }
    printf("[%s:%d]exit!\n", __func__, __LINE__);
    pthread_detach(pthread_self());
    pthread_exit(NULL);
}

void *costomer3(void *arg)
{
    arg = arg;

    printf("Hello, I'm %s!\n", __func__);
    while (1) {
        pthread_mutex_lock(&pthread_mutex);
        pthread_cond_wait(&pthread_cond, &pthread_mutex);
        printf("%s Get signal!\n", __func__);
        pthread_mutex_unlock(&pthread_mutex);
        if(goods > 20)break;
    }
    printf("[%s:%d]exit!\n", __func__, __LINE__);
    pthread_detach(pthread_self());
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    argc = argc;
    argv = argv;

    pthread_t producer_t;

    if(0 != pthread_create(&producer_t, NULL, &costomer1, NULL)){
        printf("Error in [%s:%d].\n", __func__, __LINE__);
    }

    if(0 != pthread_create(&producer_t, NULL, &costomer2, NULL)){
        printf("Error in [%s:%d].\n", __func__, __LINE__);
    }

    if(0 != pthread_create(&producer_t, NULL, &costomer3, NULL)){
        printf("Error in [%s:%d].\n", __func__, __LINE__);
    }

    sleep(1);

    if(0 != pthread_create(&producer_t, NULL, &producer, NULL)){
        printf("Error in [%s:%d].\n", __func__, __LINE__);
    }

    while(goods < 40){
        pthread_mutex_lock(&pthread_mutex);
        pthread_cond_wait(&pthread_cond, &pthread_mutex);
        printf("%s Get signal!\n", __func__);
        pthread_mutex_unlock(&pthread_mutex);
    }

    pthread_cond_destroy(&pthread_cond);
    pthread_mutex_destroy(&pthread_mutex);

    return 0;
}

 

转载请注明:OpenMind » 互斥量与条件等待配合避免竞争

喜欢 (0)