首页 > 解决方案 > 多线程编程 C

问题描述

我必须手动执行此代码并计算输出,我试了一下,找不到丢失的内容,这是代码:

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

void *thread_function(void *arg) {
    printf("Hello World :) \n");
    exit(EXIT_SUCCESS);
}

int main(void) {

    pthread_t mythread;

    if(pthread_create(&mythread, NULL, thread_function, NULL)) {
        fprintf(stderr, "Failure 1?\n");
        exit(EXIT_FAILURE);
    }

    printf("I have to wait ? \n");

    if (pthread_join(mythread, NULL)){
        fprintf(stderr, "Failure 2 ?");
        exit(EXIT_FAILURE);
    }

    printf("Goodbye Cruel World :(\n");
    return 0;
}

预期的输出是:

I have to wait ?
Hello World :)
Goodbye Cruel World :(

我得到的输出:

I have to wait ?
Hello World :)

为什么代码跳过了最后一次打印?

标签: cmultithreadingpthreads

解决方案


线程中的调用exit将在进程有机会输出“再见”消息之前终止进程。如果要终止线程,请使用pthread_exit,而不是exit


推荐阅读