Testing if initialization of static local objects is thread safe

I am trying to write a test (without examining the assembly code) to find out if a particular compiler complies with the thread-safe requirement of the C ++ 11 standard for initializing static local objects.

So far, I can come up with non-deterministic approaches (sleeping long enough on one thread to make it likely (but not sure, a problem!) That another thread has fulfilled a certain execution point).

Is there any way to do this deterministically?

+4
source share
1 answer

eg. sync voodoo (see comments) as follows:

#include <thread>
#include <mutex>
#include <chrono>
#include <iostream>

std::mutex g_mutex;

const std::chrono::seconds g_dura(1);

void log(const char* msg) {
    std::clog << std::this_thread::get_id() 
              << " "  << msg 
              << std::endl;
}

struct Asset {
    Asset () {
        log("before lock attempt");
        g_mutex.lock();
        log("after lock attempt");
        /*EDIT*/g_mutex.unlock();
    }
};

void test() {
    log("entering test()");
    static Asset asset; 
    log("leaving test()");
}

int main() {
    g_mutex.lock();
    std::thread t1(test), t2(test);
    std::this_thread::sleep_for(g_dura);

    // cleanup
    g_mutex.unlock();
    t1.join();
    t2.join();
}

( t1), init, ctor, , ( t1) init ( ) .

, , " " / " ".

g++ (Debian 4.8.2-16) .

, t1, t2 ; .

0

Source: https://habr.com/ru/post/1546461/


All Articles