如何正确使用std :: atomic_signal_fence()? [英] How to correctly use std::atomic_signal_fence()?
问题描述
cppreference.com将此功能记录为线程与在同一线程中执行的信号处理程序之间的围栏".但是我在互联网上找不到任何例子.
cppreference.com documents this function as "fence between a thread and a signal handler executed in the same thread". But I found no example on the Internet.
我想知道以下伪代码是否正确地说明了std::atomic_signal_fence()
的功能:
I wonder whether or not the following psuedo-code correctly illustrates the function of std::atomic_signal_fence()
:
int n = 0;
SignalObject s;
void thread_1()
{
s.wait();
std::atomic_signal_fence(std::memory_order_acquire);
assert(1 == n); // never fires ???
}
void thread_2()
{
n = 1;
s.signal();
}
int main()
{
std::thread t1(thread_1);
std::thread t2(thread_2);
t1.join(); t2.join();
}
推荐答案
否,您的代码未演示atomic_signal_fence
的正确用法.当您引用cppreference.com时,atomic_signal_fence
仅在信号处理程序和在同一线程上运行的其他代码之间执行同步.这意味着它不会在两个不同线程之间执行同步.您的示例代码显示了两个不同的线程.
No, your code does not demonstrate correct usage of atomic_signal_fence
. As you quote cppreference.com, atomic_signal_fence
only perform synchronization between a signal handler and other code running on the same thread. That means that it does not perform synchronization between two different threads. Your example code shows two different threads.
C ++规范包含有关此功能的以下注释:
The C++ spec contains the following notes about this function:
注意:与
atomic_thread_fence
一样,禁止编译器优化和加载与存储的重新排序,但是不会发出atomic_thread_fence本应插入的硬件防护指令.
Note: compiler optimizations and reorderings of loads and stores are inhibited in the same way as with
atomic_thread_fence
, but the hardware fence instructions that atomic_thread_fence would have inserted are not emitted.
注意: atomic_signal_fence
可用于指定线程执行的动作对信号处理程序可见的顺序.
Note: atomic_signal_fence
can be used to specify the order in which actions performed by the thread become visible to the signal handler.
这是正确的用法示例,如果没有动机的话:
Here's an example of correct, if not motivating, usage:
static_assert(2 == ATOMIC_INT_LOCK_FREE, "this implementation does not guarantee that std::atomic<int> is always lock free.");
std::atomic<int> a = 0;
std::atomic<int> b = 0;
extern "C" void handler(int) {
if (1 == a.load(std::memory_order_relaxed)) {
std::atomic_signal_fence(std::memory_order_acquire);
assert(1 == b.load(std::memory_order_relaxed));
}
std::exit(0);
}
int main() {
std::signal(SIGTERM, &handler);
b.store(1, std::memory_order_relaxed);
std::atomic_signal_fence(std::memory_order_release);
a.store(1, std::memory_order_relaxed);
}
如果遇到断言,则可以保证为真.
The assertion, if encountered, is guaranteed to hold true.
这篇关于如何正确使用std :: atomic_signal_fence()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!