pthread_join() 不工作
pthread_join() is not working
我正在试验 posix 个线程,但无法弄清楚我现在面临的问题。
Blink1 和 Blink2 在两个线程中被调用,Blink1 应该退出并让 main 加入它,之后 Blink2 应该被 main 终止。
发生的情况是 Blink1 进行了 5 次循环,但 Blink2 只是保持无限,main 中的 'printf("joined\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;
}
您正在重复使用线程标识符thrd1
来创建第二个线程。这意味着您不能 加入 与线程 1.
您实际上是在等待第二个线程。因为,第二个线程无限运行,主线程将没有机会执行 pthread_kill()
语句。
打字错误:
//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);
因为你在创建线程的时候用了两次thrd1
。
事实上,您的加入正在等待第二个线程。
我正在试验 posix 个线程,但无法弄清楚我现在面临的问题。
Blink1 和 Blink2 在两个线程中被调用,Blink1 应该退出并让 main 加入它,之后 Blink2 应该被 main 终止。
发生的情况是 Blink1 进行了 5 次循环,但 Blink2 只是保持无限,main 中的 'printf("joined\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;
}
您正在重复使用线程标识符thrd1
来创建第二个线程。这意味着您不能 加入 与线程 1.
您实际上是在等待第二个线程。因为,第二个线程无限运行,主线程将没有机会执行 pthread_kill()
语句。
打字错误:
//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);
因为你在创建线程的时候用了两次thrd1
。
事实上,您的加入正在等待第二个线程。