首页 > 解决方案 > pthread_join 不起作用,互斥锁在 C 中不起作用

问题描述

由于代码几乎相同,我得到了两个相似的问题。我是使用线程的新手,但我对这个想法和概念并不陌生,但我无法让它发挥作用......

该任务,创建两个线程(加上主线程),一个以短延迟打印 hello moon 三次,另一个以长延迟打印 hello world 3 次,一个接一个。

代码的第一个版本出现了一个问题,即即使我使用连接,main 有时也会在线程完成其工作之前退出。这是代码:

更新:使用 pthread_join(&....); 这不是一个好主意。我应该使用 pthread_join(...); (没有&)这部分似乎现在可以正常工作。

#include <stdio.h>
#include <stdlib.h>
#include "wrapper.h"
#include <pthread.h>
#include <sys/time.h>

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


void *HelloMoon (void * arg){
    pthread_mutex_lock(&mutex);

    struct timeval stop, start;
    int i = 0;

    gettimeofday(&start, NULL);
        while(i < 3){
            gettimeofday(&stop, NULL);
            if((stop.tv_usec-start.tv_usec)>=20000){
                printf("Hello Moon!\n");
                gettimeofday(&start, NULL);
                i++;
            }
        }

    pthread_mutex_unlock(&mutex);

    return NULL;
}


void *printHelloWorld(void* arg){

    pthread_mutex_lock(&mutex);

    struct timeval stop, start;

    int i = 0;

    gettimeofday(&start, NULL);
    while(i < 3){
        gettimeofday(&stop, NULL);
        if((stop.tv_sec-start.tv_sec)>=1){
            printf("Hello world!\n");
            gettimeofday(&start, NULL);
            i++;
        }
    }

    pthread_mutex_unlock(&mutex);

    return(NULL);

}



int main(int ac, char * argv)
{

    pthread_t thread_id1, thread_id2;

    pthread_create(&thread_id2, NULL, HelloMoon, NULL);
    pthread_create(&thread_id1, NULL, printHelloWorld, NULL);

    pthread_join(&thread_id2, NULL);
    pthread_join(&thread_id1, NULL);


    return(0);
}

第二个代码在 main 中使用了一个 while 循环来使行为永远重复。这“解决”了 main 退出的问题,但有时一个线程运行两次,使其打印 6 次而不是 3 次。这是为什么?代码:

更新:我认为这是因为循环每次运行时都会创建两个新线程,使线程总数大于两个,这反过来又导致多个线程具有相同的 id 会导致这种有趣的行为。我是对还是错?

int main(int ac, char * argv)
{

    pthread_t thread_id1, thread_id2;

    while(1==1){
        pthread_create(&thread_id2, NULL, HelloMoon, NULL);
        pthread_create(&thread_id1, NULL, printHelloWorld, NULL);

        pthread_join(&thread_id2, NULL);
        pthread_join(&thread_id1, NULL);
    }


    return(0);
}

最后一个问题,让线程一个接一个地永远运行的最好方法是什么?while 循环是个好主意吗?线程的变量“i”是否相同?我认为不是,但一位消息人士说是这样,所以我想确定一下。

标签: cmultithreadingpthreads

解决方案


pthread_join期望线程 id 而不是指向它的指针作为第一个参数。

pthread_join(&thread_id2, NULL);
pthread_join(&thread_id1, NULL);

应该

pthread_join(thread_id2, NULL);
pthread_join(thread_id1, NULL);

推荐阅读