【发布时间】:2026-02-23 19:00:01
【问题描述】:
我正在尝试使用此示例代码找出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 */
有两件事我不太确定:
当我们使用 pthread_create 时 - 我正在传递“a”参数的地址, 但是这个参数是否被“保存”在 PrintVar 函数的“arg”下? 例如,如果我正在使用:
PrintVar(void *blabla),并想从主函数传递 2 个参数:int a = 10, int b= 20.. 我该怎么做?为什么需要 pthread_exit?这意味着 - 等待进程结束 - 但是如果我不使用那条线,我会得到什么情况?
非常感谢!
【问题讨论】:
-
参考第二个问题:你试过会发生什么吗?提示:在
PrintVar()的开头添加sleep(1);并注释掉对pthread_exit()的调用。 -
这些是多线程的基本问题,也是相当聪明的问题。 computing.llnl.gov/tutorials/pthreads也许一本好书会帮助更多
-
@alk 我在没有睡眠的情况下使用它,它的工作方式与没有任何线程的情况相同..这就是为什么我很困惑:(我会尝试你的建议!谢谢
标签: c multithreading unix pthreads