我最近一直在学习线程,但我对一些事情感到困惑。我以为我们只能从一个线程变量创建一个线程,并且该线程只能执行一项作业,但在下面的代码中,我从一个全局线程变量创建四个线程,并且它们同时打印。我所说的“同时”是指所有函数都会运行,而无需等待前一个函数完成。
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
pthread_t thread;
void *func4() {
int i;
for(i = 0; i < 5; i++){
printf("/\n");
sleep(1);
}
}
void *func3() {
pthread_create(&thread, NULL, func4, NULL);
int i;
for(i = 0; i < 5; i++){
printf("*\n");
sleep(1);
}
pthread_join(thread, NULL);
}
void *func2() {
pthread_create(&thread, NULL, func3, NULL);
int i;
for(i = 0; i < 5; i++){
printf("-\n");
sleep(1);
}
pthread_join(thread, NULL);
}
void *func1() {
pthread_create(&thread, NULL, func2, NULL);
int i;
for(i = 0; i < 5; i++){
printf("+\n");
sleep(1);
}
pthread_join(thread, NULL);
}
int main() {
pthread_create(&thread, NULL, func1, NULL);
pthread_join(thread, NULL);
return 0;
}
这是一个概念还是我知道或使用了错误的东西?
您不能“从”线程变量创建 pthread。您调用
pthread_create
创建一个线程,并告诉它把线程 ID 放在哪里。
您所做的是创建四个线程并告诉
pthread_create
将线程 ID 放在同一位置。这会导致多次尝试将线程 ID 值存储在一个对象中。充其量,这只会在对象中留下一个有效的线程 ID,因此您会丢失其他值,并且 pthread_join
调用将不会收到正确的 ID。 (在最坏的情况下,写入尝试可能会相互冲突并损坏对象,从而不会在其中留下有效的 ID,但这在现代情况下不太可能发生。)