【问题标题】:Consumer-producer. No errors. Works sometimes. Why?消费者-生产者。没有错误。有时工作。为什么?
【发布时间】:2015-04-05 13:32:18
【问题描述】:
  1. 为什么这段代码每次都给我不同的输出?
  2. 为什么它没有完成循环?
  3. 我应该怎么做才能让它完成循环? (尽管有上下文切换)?
  4. 还有什么我做错了吗?

任何帮助将不胜感激!

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define MAX 10

int buffer[MAX];
int fill = 0;
int use = 0;
int count = 0;

int loops = 15; 


void put(int value) {
    buffer[fill] = value;
    fill = (fill + 1) % MAX;
    count++;
    printf("putting %d\n", value);
}

int get() {
    int tmp = buffer[use];
    use = (use + 1) % MAX;
    count--;
    return tmp;
}

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_fill = PTHREAD_COND_INITIALIZER;

void *producer(void *arg) {
    printf("producer starts\n");
    int i;
    for (i = 0; i < loops; i++) {
        pthread_mutex_lock(&mutex); // p1
        while (count == MAX) // p2
            pthread_cond_wait(&c_empty, &mutex); // p3
        put(i); // p4
        pthread_cond_signal(&c_fill); // p5
        pthread_mutex_unlock(&mutex); // p6
    }
    return NULL;
}

void *consumer(void *arg) {
    printf("consumer starts\n");
    int i;
    for (i = 0; i < loops; i++) {
        pthread_mutex_lock(&mutex); // c1
        while (count == 0) // c2
            pthread_cond_wait(&c_fill, &mutex); // c3
        int tmp = get(); // c4
        pthread_cond_signal(&c_empty); // c5
        pthread_mutex_unlock(&mutex); // c6
        printf("consuming: %d\n", tmp);
    }
    return NULL;
}


int main(int argc, char *argv[]) {
    printf("parent: begin\n");
    pthread_t p, x;
    pthread_create(&p, NULL, producer, NULL);
    pthread_create(&x, NULL, consumer, NULL);


    printf("parent: end\n");
    return 0;
}

生成文件:

all: wcountb
wcountb: wcountb.c
    gcc -g -Wall -o wcountb wcountb.c -lpthread

【问题讨论】:

    标签: c multithreading buffer mutex condition-variable


    【解决方案1】:

    在正文结束时,您应该调用pthread_join,如下所示:

      ...
      pthread_join(p, NULL);
      pthread_join(x, NULL);
      return 0;
    }
    

    没有那个调用,线程就会被创建,当你到达main() 的末尾时,你的程序就会终止,因此你的线程可能能够完成它们的工作,或者不能,这就解释了事实上,有时您的代码会起作用。

    pthread_join() 函数将暂停调用线程的执行,直到目标线程终止,除非目标线程已经终止。

    取自manualpthread_join()

    一个几乎相关的问题在于here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多