【问题标题】:pthread_join doesn't workpthread_join 不起作用
【发布时间】:2012-12-20 16:27:38
【问题描述】:

我想要完成的事情:

在主函数中创建了两个线程。他们用数字 5 增加一个全局变量。并向消费者线程发送一个递减变量的信号。在每次递减之间的消费者线程中,显示​​当前值。主线程必须等到所有线程都完成后才退出。

我得到了什么:

有时主函数在消费者有机会显示结果之前就退出了。我正在使用 pthread_join,但它返回错误代码 3。

任何想法如何获得想要的结果?

代码如下。

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

static pthread_mutex_t mtx;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *producer(void *arg);
void *consumer(void *arg);
static int avail = 0;

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

    pthread_t cons1, prod1, prod2;

    int status;
    int t1;
    int t2;
    int t3;

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_mutexattr_t mtxAttr;
    pthread_mutexattr_settype(&mtxAttr, PTHREAD_MUTEX_ERRORCHECK);
    pthread_mutex_init(&mtx, &mtxAttr);

    t1 = pthread_create(&prod1, &attr, producer, NULL);
    if(t1 != 0){
    perror("problem1");
    }
    t2 = pthread_create(&prod2, &attr, producer, NULL);
    if(t2 != 0){
    perror("problem2");
    }
    t3 = pthread_create(&cons1, &attr, consumer, NULL);
    if(t3 != 0){
    perror("problem3");
    }

    status = pthread_join(t1, NULL);
    if(status != 0){
    perror("can't join1");
    }

    status = pthread_join(t2, NULL);
    if(status != 0){
    perror("can't join2");
    printf("\n%d\n", status);
    }
    status = pthread_join(t3, NULL);
    if(status != 0){
    printf("%s",strerror(errno));
    }
    printf("\nend result \t%d\n",avail);
    printf("fin\n");
    //while(1){}
    return 0;
}

void *producer(void *arg){
    int s;
    printf("producer\n");
    s = pthread_mutex_lock(&mtx);
    avail+=5;
    s = pthread_mutex_unlock(&mtx);
    s = pthread_cond_signal(&cond);
    pthread_exit(NULL);
}

void *consumer(void *arg){
    int s;
    while(1) {
    s = pthread_mutex_lock(&mtx);
    if(s !=0 ){
        perror("lock err");
    }
    while (avail == 0) {
        s = pthread_cond_wait(&cond, &mtx);
    }
    while (avail > 0) {
        avail--;
        printf("Temp: %d \n",avail);
    }

    s = pthread_mutex_unlock(&mtx);
    }
    printf("done");
    pthread_exit(NULL);
}

【问题讨论】:

    标签: c multithreading join pthreads


    【解决方案1】:

    不要加入 t1t2t3。这些是pthread_create() 函数的返回码。在prod1prod2cons1 上使用pthread_join()。请使用-Wall -Wextra 编译。

    【讨论】:

    • 谢谢!下次最好小心点。
    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 2016-10-27
    • 2016-09-19
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2016-06-02
    相关资源
    最近更新 更多