Explicit thread safety keyword/macro for compile time checking

Viewed 58

I'm currently working on a medium-to-large C++ application which has a networked interface (similar to a multithreaded RPC service).

The networked interface communicates with a fairly complex application state. I think I've done a good job of keeping the non-thread-safe state (maps, vectors, etc) surrounded by mutexes, but I'm not sure.

I think it'd be really cool if I could specify which functions are thread safe and have it checked at compile time so that I don't have to run static analysers on my code. I'm fine with annotating all of my functions.

I'm currently stuck trying to come up with a way to fulfill the following examples with macros/template metaprogramming, but if this is natively possible, or a library to do this already exists, I'd rather use that.

void not_thread_safe foo() {
    // some unsafe code
}

void called_from_multiple_threads bar() {
    foo(); // causes compile time error
}

// note the thread_safe keyword/macro, vs the above not_thread_safe
void thread_safe foo() {
    std::lock_guard lock(some_mutex);
    // unsafe code
}

void called_from_multiple_threads bar() {
    foo(); // no error
}
void not_thread_safe foo() {
    // unsafe code
}

void blah() {
    foo(); // bonus points if it catches this too (should be an error)
}

void called_from_multiple_threads bar() {
    blah();
}
0 Answers
Related