为什么程序不等待pthread

SCG*_*SCG 1 c linux pthreads

程序没有执行函数 1 的整个 for 循环。我认为加入线程会使程序等待胎面结束。

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

void* func1(void* arg) {
    for(int i=0;i<10;i++) {
        printf("Func 1: %d\n", i);
        sleep(1);
    }
    return NULL;
}

void func2(void) {
    for(int i=0;i<5;i++) {
        printf("Func 2: %d\n", i);
        sleep(1);
    }
}

int main(void) {
    pthread_t new_thread;
    pthread_create(&new_thread, NULL, func1, NULL);
    func2();
    pthread_join(&new_thread, NULL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

来自pthread_join

   int pthread_join(pthread_t thread, void **retval);
Run Code Online (Sandbox Code Playgroud)

如您所见,第一个参数是 apthread_t但您正在通过pthread_t*- 这就是问题所在。所以你应该使用:

pthread_join(new_thread, NULL);
Run Code Online (Sandbox Code Playgroud)

请注意,如果您对pthread_*函数调用进行了错误检查,您就会发现问题所在。例如,运行您的代码:

errno = pthread_join(&new_thread, NULL);
if (errno) perror("pthread_join");
Run Code Online (Sandbox Code Playgroud)

看看它说了什么。

同样,启用编译器警告(例如-Wall -Wextra)也会有所帮助。