c - 为什么要使用pthread_exit?

标签 c multithreading unix pthreads

我正在尝试使用以下示例代码找出 pthread_exit 的用法:

void* PrintVar(void* arg)
 { 
   int * a = (int *) arg; // we can access memory of a!!!
    printf( "%d\n", *a); 
 } 

int main(int argc, char*argv[]) 
 { 
   int a, rc;
    a = 10; 
   pthread_t thr; 
   pthread_create( &thr, NULL, PrintVar, &a ); 

  //why do I need it here?//
  pthread_exit(&rc); /* process continues until last  
                                threads termintates */

有两件事我不太确定:

  1. 当我们使用 pthread_create 时 - 我传递“a”参数的地址, 但是这个参数是否被“保存”在 PrintVar 函数的“arg”下? 例如,如果我使用: PrintVar(void *blabla) ,并且想从主函数传递 2 个参数: int a = 10, int b= 20 .. 如何我可以这样做吗?

  2. 为什么需要 pthread_exit?这意味着 - 等待进程结束 - 但如果我不使用该行,会出现什么情况?

非常感谢!

最佳答案

  1. when we are using pthread_create - I'm passing 'a' parameter's address, but is this paramter being "saved" under "arg" of the PrintVar function?

“原创”a ( main 中定义的)不会被复制,您只是传递一个指向它的指针。

for example if I was using : PrintVar(void *blabla) , and wanted to pass 2 parameters from main function : int a = 10, int b= 20 .. how can I do that?

将这两个值放入 struct 中并将指向此类结构的指针作为参数传递给 pthread_create (因此,PrintVar 将接收这样的指针,并且能够检索这两个值)。

and my second question is why the pthread_exit needed? it means - wait for proccess to end - but what scenario can I get if I won't use that line?

pthread_exit如果其他线程仍在运行,则终止当前线程而不终止进程;从 main 返回相反,相当于调用 exit就标准而言,应该“终止程序”(从而隐式杀死所有线程)。

现在,作为与线程无关的 C 标准(直到 C11)以及对各种 Unix 中线程的支持是一个相对较新的添加,具体取决于 libc/kernel/无论版本 exit可能会或可能不会仅杀死当前线程或所有线程。

不过,在当前版本的 libc 中,exit (因此从 main 返回)应该终止进程(及其所有线程),实际上使用系统调用 exit_group在 Linux 上。

请注意 similar discussion适用于 Windows CRT。

关于c - 为什么要使用pthread_exit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399631/

相关文章:

c - 整数被重复?

c - 将指针传递给具有指向 const 指针的形式参数的函数时的未定义行为?

java - 如何从 Thread 对象重新绘制 jTree?

bash - 在 bash 脚本中运行 awk

perl - 如何有效地在两个级别上对大文件进行排序?

c - 在Linux中,如果不使用GDB进行实时调试,如何找到C程序挂起时的状态?

c - 从 g_variant_new () 获取结果

Android MediaRecorder 启动失败,处于无效状态 4

java - 如果线程自身调用 join() 会发生什么

linux - 如何向 SSH 提供密码?