简体   繁体   English

多线程编程 C

[英]Multi-threaded Programming C

I have to execute this code manually and figure the output, I tried it out and could not find out what am missing, here's the code:我必须手动执行此代码并计算输出,我尝试了一下,但找不到遗漏的内容,这是代码:

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

The expected output is:预期的输出是:

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

The output I got:我得到的输出:

I have to wait ?
Hello World :)

Why the code skipped the last print?为什么代码跳过了最后一次打印?

The call to exit in the thread will terminate the process before it has a chance to output the "Goodbye" message.线程中的exit调用将在进程有机会输出“再见”消息之前终止进程。 If you want to terminate a thread, use pthread_exit , not exit .如果要终止线程,请使用pthread_exit ,而不是exit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM