[英]Is atomic increase and comparsion thread-safe
I'm writing multithreaded socket class. 我正在编写多线程套接字类。 BelowBounds() function can be invoked from multiple threads simultaneously, i need to prevent using mutexes.
可以同时从多个线程调用belowBounds()函数,我需要防止使用互斥锁。 Does this code is thread-safe ?
此代码是否是线程安全的?
class UDPSocketHT
{
public:
std::atomic<size_t> m_nSimultaneousRecvCalls;
std::atomic<size_t> m_nPendingOperations;
//...
bool UDPSocketHT::BelowBounds ( )
{
return ( !m_nSimultaneousRecvCalls || ( m_nPendingOperations + 1 <= m_nSimultaneousRecvCalls ) ) ? true : false;
}
}
Or i must write in this way? 还是我必须以这种方式写?
bool UDPSocketHT::BelowBounds ( )
{
size_t x = m_nSimultaneousRecvCalls;
size_t y = m_nPendingOperations;
return ( !x || ( y + 1 <= x) ) ? true : false;
}
Both of your alternatives are unsafe. 您的两种选择都不安全。 Each atomic variable by itself is atomic, but using two of them in a single statement is not.
每个原子变量本身就是原子的,但是在单个语句中却不能使用两个原子变量。
You can wrap your check in a mutex or come up with a way to use a single atomic. 您可以将支票包装在互斥锁中,也可以提出使用单个原子的方法。
What operations on std::atomic
are atomic? std::atomic
上的哪些操作是原子的?
operator=
stores a new value atomically operator=
原子存储一个新值
load()
or operator T
(using in an expression) reads the value atomically load()
或operator T
(在表达式中使用)原子读取值
operator++
increments a value atomically operator++
自动增加一个值
compare_exchange_weak/strong
check and set the value atomically compare_exchange_weak/strong
检查并自动设置值
Using two atomics in an expression is not atomic: a + b
will read a
atomically, then read b
atomically, but anything can happen in between reading a
and b
; 在表达式中使用两个原子不是原子的:
a + b
将自动读取a
原子, 然后自动读取b
,但是在读取a
和b
之间可能发生任何事情; by the time you read b
, a
can already have another value. 到您阅读
b
, a
已经可以具有另一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.