【问题标题】:Multi-threaded Programming C多线程编程 C
【发布时间】:2020-03-08 17:22:01
【问题描述】:

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

#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 :)

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

【问题讨论】:

  • 我假设线程中的出口在打印之前终止了主线程?尝试改用 pthread_exit。
  • 退出程序会杀死所有线程。要么从线程函数返回,要么使用线程退出函数。

标签: c multithreading pthreads


【解决方案1】:

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

【讨论】:

  • 不只是“可以”,在这种情况下会,因为主线程在继续打印再见消息之前尝试加入子线程,并且子线程无条件致电exit()。
猜你喜欢
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2020-12-02
  • 1970-01-01
相关资源
最近更新 更多