c - pthread_join() 不工作

标签 c pthreads

<分区>

我正在试验 posix 线程,但无法弄清楚我现在面临的问题。

Blink1 和 Blink2 在两个线程中被调用,Blink1 应该退出并让 main 加入它,之后 Blink2 应该被 main 终止。

发生的事情是 Blink1 进行了 5 次循环,但 Blink2 只是保持无限,'printf("joined\n");' in main 永远不会被调用。

我错过了什么?又一次太愚蠢以至于无法阅读手册?

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

int i = 0;

void *blink1(){
    int j;
    for ( j = 0; j < 5; j++){
        //activate
        printf("blink1: i = %d ON\n", i);
        sleep(1);
        //deactivate
        printf("blink1: i = %d OFF\n", i);
        sleep(1);
    }
    pthread_exit(NULL);
}

void *blink2(){
    while (1){
        //activate
        printf("blink2: i = %d ON\n", i);
        sleep(1);
        //deactivate
        printf("blink2: i = %d OFF\n", i);
        sleep(1);
        i++;
    }
}

int main(){
    pthread_t thrd1, thrd2;

    //start threads
    pthread_create(&thrd1, NULL, &blink1, NULL);
    pthread_create(&thrd1, NULL, &blink2, NULL);

    //output pid + tid
    printf("PID: %d ; TID1: %lu ; TID2: %lu\n", getpid(), thrd1, thrd2);

    //wait for thread 1
    pthread_join(thrd1, NULL);
    printf("joined\n");

    //terminte thread 2
    pthread_kill(thrd2, 15);

    return 0;
}

最佳答案

您正在重用线程标识符thrd1 来创建第二个线程。这意味着您不能加入线程 1。

您实际上是在等待第二个线程。因为,第二个线程无限运行,主线程将没有机会执行 pthread_kill() 语句。

关于c - pthread_join() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37256593/

相关文章:

c - 使用fgets时,我的指针地址错误

c - C中变量名下划线前分号的可能原因

c - 如何使 pthreads 池运行任意例程

c - 是否可以确定持有互斥锁的线程?

c - Pthreads,尝试使用信号量从多个线程打印数字部分

c - 在 C 语言中打印和清除,无需库

c++ - Cuda cudaMemcpy 和 cudaMalloc

c++ - 如何用 pthread 捕获堆栈溢出?

C 将共享变量传递给 pthread

C 在 struct free() 中动态分配结构