C++静态初始化是否会抛出system_error?线程安全初始化相关问询
C++11静态变量初始化的线程安全与system_error抛出问题
自C11起,静态变量的初始化具备线程安全性,通常通过**双重检查锁定(DCL)**实现。DCL需要使用互斥锁同步未完成的初始化操作,即便不采用DCL,初始化同步也离不开互斥锁。那么C标准中是否有相关规定,指出静态变量在构造函数实际调用前首次使用时,可能会抛出system_error?
尝试运行以下代码:
#include <iostream> #include <thread> #include <vector> using namespace std; template<unsigned Thread> struct SleepAtInitialize { SleepAtInitialize() { this_thread::sleep_for( 1s ); } }; int main() { auto unroll = []<size_t ... Indices>( index_sequence<Indices ...>, auto fn ) { ((fn.template operator ()<Indices>()), ...); }; constexpr unsigned N_THREADS = 10; vector<jthread> threads; threads.reserve( N_THREADS ); unroll( make_index_sequence<N_THREADS>(), [&]<unsigned Thread>() { threads.emplace_back( [&]<unsigned IObj>( integral_constant<unsigned, IObj> ) { static SleepAtInitialize<IObj> guard; }, integral_constant<unsigned, Thread>() ); } ); }
运行后可以发现,这类初始化操作并没有统一的中央互斥锁。
内容的提问来源于stack exchange,提问作者Edison von Myosotis
相关产品推荐
相关产品推荐

