c++ - 当子线程崩溃和主线程等待加入时会发生什么?

标签 c++ multithreading pthreads

在下面的程序中,我创建了一个 pthread_t 线程 1,它在函数 func() 中崩溃。我对 main() 中的 pthread_join 命令到底发生了什么很感兴趣。

我在程序下方运行并通过打印“完成”正常退出。不知道为什么?

#include <iostream> 
#include <string> 
#include <vector> 
#include <map> 
#include <cstring> 
#include <climits> 
#include <cstdio> 
#include<pthread.h>
#include <stdlib.h>
using namespace std; 

void* func(void *data)
{
    cout<<"Calling func"<<(long)(data)<<endl;
    int *a;
    cout<<a[2]<<endl;
    pthread_exit(0);
}

int main( )
{ 
    pthread_t thread1;
    pthread_create(&thread1, 0 , &func, (void*)2);
    pthread_join(thread1, NULL);
    cout<<"complete"<<endl;

}

最佳答案

在您的情况下,该过程本身会出现段错误。

如果您将 NULL 分配给 a,您会发现它很可能会崩溃。在当前代码中,您以非确定性方式调用 aa 引用了一些随机位置。因此行为是不确定的。有时您会在 main 中看到日志语句,有时程序会崩溃。如果程序在这样的执行中崩溃,那你就幸运了

如果线程执行 NULL 指针取消引用,它将关闭整个进程。它是进程崩溃而不是线程崩溃。

关于c++ - 当子线程崩溃和主线程等待加入时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147942/

相关文章:

c++ - 读写操作的线程安全C++

ios - 由于 NSURLSession/NSURLConnection HTTP 加载失败,无限 pthread 创建崩溃应用程序

c++ - pthreads 和 C++

c++ - 在不同函数中更改结构中的值

c# - 任务与线程池

.net - 使用互锁

c - 计算多进程程序的运行时间的最佳方法是什么?

c# - 应用程序在基于 .NET 的 COM 对象的 CoCreateInstance 期间挂起

C++ : How to send a struct from client to server through socket and serialize it?

c++ - 使用模板获取数组的大小和结束地址