C - pthread函数重用 - 局部变量和竞争条件
如果我定义一个线程函数来重用主线程也使用的另一个函数......是否可能存在竞争条件?同一函数中的局部变量是否跨线程共享?在这种情况下,函数 do_work 在 thread_one 线程和主线程中都使用。函数 do_work 中的局部变量 x 是否可以被两个线程修改,从而产生意外结果?
void *thread_one() {
int x = 0;
int result;
while(1) {
for(x=0; x<10; x++) {
result = do_work(x);
}
printf("THREAD: result: %i\n", result);
}
}
int do_work(int x) {
x = x + 5;
return x;
}
int main(int argc, char**argv) {
pthread_t the_thread;
if( (rc1 = pthread_create( &the_thread, NULL, thread_one, NULL)) ) {
printf("failed to create thread %i\n", rc1);
exit(1);
}
int i = 0;
int result = 0;
while(1) {
for(i=0; i<12; i+=2) {
result = do_work(i);
}
printf("MAIN: result %i\n", result);
}
return 0;
}
If I define a thread function that reuses another function that the main thread also uses....is it possible that there can be a race condition? Are the local variables in the same function shared across threads? In this case the function do_work is used in both the thread_one thread and the main thread. Can the local variable x in the function do_work be modified by both threads so it creates an unexpected result?
void *thread_one() {
int x = 0;
int result;
while(1) {
for(x=0; x<10; x++) {
result = do_work(x);
}
printf("THREAD: result: %i\n", result);
}
}
int do_work(int x) {
x = x + 5;
return x;
}
int main(int argc, char**argv) {
pthread_t the_thread;
if( (rc1 = pthread_create( &the_thread, NULL, thread_one, NULL)) ) {
printf("failed to create thread %i\n", rc1);
exit(1);
}
int i = 0;
int result = 0;
while(1) {
for(i=0; i<12; i+=2) {
result = do_work(i);
}
printf("MAIN: result %i\n", result);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。局部变量不在线程之间共享。
No. Local variables aren't shared across threads.
不,线程的局部变量不在线程之间共享。
具体来说,每个线程都有自己的一组寄存器和堆栈。然而,代码和全局数据是共享的。
No, local variables of thread are not shared accross threads.
In detail, each thread has its own set of registers and stack. However, code and global data are shared.
否,因为
x
是局部变量。每个线程都使用自己的x
变量,因此线程不可能修改其他线程的x
。No since
x
is a local variable. Every thread works with his ownx
variable, so there's no possibility for a thread to modify other thread'sx
.不,更重要的一点是,即使在同一线程中,局部(自动)变量也不会在函数的多个实例之间共享。这就是递归的工作原理以及函数可重入的原因。
No, and the more important point is that local (automatic) variables are not shared between multiple instances of a function even in the same thread. This is how recursion works and what makes it possible for functions to be reentrant.