2016-05-16 84 views
1

我正在试验posix线程,只是无法弄清楚我现在面临的问题。pthread_join()不工作

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

会发生什么是Blink1做5次循环,但Blink2只是保持无限,'printf(“加入\ n”);'在主要从未被调用。

我错过了什么?又一次太傻看了手册?

#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; 
} 
+4

您是否注意到'thrd1'使用了两次?这意味着它被覆盖,所以你实际上加入了你的第二个线程,永远不会结束。 –

回答

4

重用创建的第二个线程的线程标识符thrd1。这意味着你不能加入与线程1.

您正在等待第二个线程。由于第二个线程无限运行,主线程将不会有机会执行pthread_kill()语句。

+0

我发现这是因为编译警告。 @Siraja,确保在编译时使用高警告级别。 –

+0

哇,我一直在阅读创建加入的人的页面,并杀了半个小时,最后它只是一个愚蠢的复制粘贴错误..非常感谢! – Carl

+1

@Siraja另外,你还有一个微妙的问题。在访问变量'i'时有一个* data race *(它是* undefined *),因为它是由两个线程通过任何同步访问的。我还建议不要硬编码信号编号(15),而是使用signal.h中的相应宏 –

3

错字:

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

大概应该是:

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

因为在创建线程时使用thrd1两次。

实际上,您的连接正在等待第二个线程。