从C中的两个线程访问变量 [英] Accessing variable from two threads in C

查看:142
本文介绍了从C中的两个线程访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

int attempts = 0;
while(ptr== NULL && attempts < 60) {
        sleep(1000);
        attempts++;
    }

连续循环等待指针被另一个线程设置.另一个线程将简单地完成

that continuously loops waiting for the pointer to be set by another thread. The other thread will simply do

ptr = //some value

我的问题是,这安全吗?这会导致任何内存损坏,导致以后很难调试错误情况吗?

My question is, is this safe? Will this cause any memory corruption that lead to hard to debug error conditions later?

P.S:我知道由于缺少volatile关键字,编译器可能会优化ptr.这对我来说无关紧要.我只担心这是否会导致代码的其他不相关部分出现问题.

P.S: I'm aware that the compiler may optimise out the ptr due to the lack of the volatile keyword. That doesn't matter as much to me. I'm only concerned whether this will cause problems to other unrelated parts of the code.

推荐答案

至少,ptr可以声明为volatile;但这不够.您真的想要原子操作.使用 C11 ,您具有<stdatomic.h>标准标头. 最近的GCC具有原子内置函数. ptr的访问和写入(在您的其他线程"中)都应该是原子的!

At the very least, ptr could be declared as volatile ; but that is not enough. You really want atomic operations. With C11 you have <stdatomic.h> standard header. And recent GCC has atomic builtins that you should use. Both the access and the writing (in "your other thread") of your ptr should be atomic!

实际上(不使用原子操作),您会观察到的行为是未定义的行为,并且可能变化很大(使用不同的处理器,不同的编译器等).

Actually (without using atomic operations) the behavior that you would observe is undefined behavior and could vary a lot (with different processors, different compilers, etc...).

遗憾的是,在许多x86处理器上,您可能没有注意到UB

您需要编译器通过发出特定的机器指令来强制执行/使用缓存一致性.

You need the compiler to enforce/use cache coherence by emitting particular machine instructions.

您还可以将条件变量与互斥锁一起使用,或将某些信号灯.

You could also use condition variables with mutex locks, or some semaphore.

使用最新的 GCC (至少4.9),您可以考虑使用-fsanitize=thread和/或-fsanitize=address(用于调试),如果目标处理器支持的话.

With a recent GCC (at least 4.9) you might consider compiling with -fsanitize=thread and/or -fsanitize=address (for debugging) if your target processor supports that.

顺便说一句,您的内存损坏可能是完全无关的.您可以考虑使用许多平台支持的valgrind(最好编译您的程序使用-g,并且您可以尝试使用gcc -O1 -g进行编译.)

BTW, your memory corruption might be completely unrelated. You could consider using valgrind which is supported on many platforms (it is better to compile your program with -g and you could try to compile with gcc -O1 -g if you wanted to).

我还建议您使用最新的工具(2014年9月发布的GCC 4.9版,最新的binutils,最新的gdb,最新的libc,最新的内核....)

I also recommend using recent tools (recent version 4.9 of GCC -in september 2014-, recent binutils, recent gdb, recent libc, recent kernel....)

这篇关于从C中的两个线程访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆