c - 多线程编程 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 :)
为什么代码跳过了最后一次打印?
解决方案
线程中的调用exit
将在进程有机会输出“再见”消息之前终止进程。如果要终止线程,请使用pthread_exit
,而不是exit
。
推荐阅读
- angular - 在多个项目中以角度重用组件的最佳方法是什么?
- javascript - 如何正确地将 js 库添加到 laravel 项目中
- java - 检查谓词泛型的类型
- javascript - 如何在javascript中从父类触发子实例的事件?
- pyspark - 如何更新pyspark中的列值?
- maven - Maven "also-make" 的行为
- python - 如何在 tkinter 的同一个变量中绑定一个又一个函数?
- dbt - 如何修复“无法解析”的 sqlfluff lint 错误
- android - Android 11(仅限)FragmentManager 崩溃 - FragmentManager 已被销毁
- sqlite - 使用 Jetbrains 的 Datagrip 时如何保存 sqlite 数据库