nas*_*ass 3 c multithreading arguments local-variables
我正在研究gcc,我想知道这是否可行:
我有一个函数(NOTmain但是aLocalFn),我在其中声明了一个局部变量.然后我将此局部参数作为线程参数传递.它可行吗?或者有机会(取决于先运行的是什么)在运行threadFunction之前aLocalVar会丢失,而引用idxPtr将指向无意义?
int *threadFunction(void *idxPtr){
int rec_idx=(int) *idxPtr;
//work in the thread with this variabel rec_idx
}
int aLocalFn(){
int aLocalVar=returnsRecordIndex();
pthread_create(&thread_id,&attr_detached,threadFunction, &aLocalVar)!=0)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助
此代码不正确.该函数aLocalFn可以在线程函数开始执行之前返回.因此,当线程函数读取局部变量时,该变量的范围可能已经结束.
令人困惑的是,这段代码似乎很有效,至少在某些时候.但是,它不正确,您应该使用堆分配的内存.
| 归档时间: |
|
| 查看次数: |
2822 次 |
| 最近记录: |