gcc中线程安全的原子操作 [英] Thread-safe atomic operations in gcc

查看:180
本文介绍了gcc中线程安全的原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我工作的程序中,我有很多代码如下:

  pthread_mutex_lock(& frame-> ;互斥体); 
frame-> variable = variable;
pthread_mutex_unlock(& frame-> mutex);

如果中间指令可以被原子存储替换,这显然会浪费CPU周期。我知道gcc完全可以做到这一点,但是我一直无法找到关于这种简单线程安全的原子操作的大量文档。我将如何用原子操作替换这组代码?



(我知道简单的商店在理论上应该是原子的,但我不希望在这个过程的某个时刻,优化器并没有搞乱他们的原子性。)



澄清:我不需要它们是严格原子的;这些变量仅用于线程同步。也就是说,线程B读取值,检查它的正确性,如果它不正确,它会睡觉。所以,即使线程A更新了值并且线程B没有意识到它的更新,这也不是问题,因为这只是表示线程B在没有真正需要的时候睡觉,当它醒来时,值会是正确的。

解决方案

您可以检查gcc文档。对于当前的gcc版本(4.3.2),它将是第5.47章原子内存访问的内置函数 - 对于其他gcc版本,请检查您的文档。它应该在第5章C语言系列的扩展中。

顺便说一句,C编译器绝对不能保证简单的存储操作是原子操作。你不能依靠这个假设。为了使机器操作码自动执行,它需要LOCK前缀。


In a program I work on, I have a lot of code as follows:

pthread_mutex_lock( &frame->mutex );
frame->variable = variable;
pthread_mutex_unlock( &frame->mutex );

This is clearly a waste of CPU cycles if the middle instruction can just be replaced with an atomic store. I know that gcc is quite capable of this, but I haven't been able to find much documentation on such simple thread-safe atomic operations. How would I replace this set of code with an atomic operation?

(I know that simple stores should theoretically be atomic, but I don't want to have to hope that the optimizer isn't screwing up their atomic-ness at some point in the process.)

Clarification: I do not need them to be strictly atomic; these variables are solely used for thread synchronization. That is, Thread B reads the value, checks if its correct, and if its not correct, it sleeps. So even if Thread A updates the value and Thread B doesn't realize its updated, that isn't a problem, since that just means Thread B sleeps when it didn't really need to, and when it wakes up, the value will be correct.

解决方案

You could check the gcc documentation. For the current gcc version (4.3.2) it would be chapter 5.47 Built-in functions for atomic memory access - for other gcc versions please check your docs. It should be in chapter 5- Extensions to the C Language Family.

Incidentally, the C compiler makes absolutely no guarantee as to simple store operations being atomic. You cannot rely on that assumption. In order for a machine opcode to be executed atomically, it needs the LOCK prefix.

这篇关于gcc中线程安全的原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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