简体   繁体   中英

C++ constexpr thread_local id

Is there any way to get a different value in a constexpr thread_local variable for every thread?

constexpr thread_local someType someVar = ......;

It seems like constexpr thread_local is supported but the thread_local indicator doesnt seem to do anything in this case.

If you think about your question, you yourself can see why this is not possible.

What is constexpr ?

According to the informal standard site cppreference :

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time .

The compiler has to resolve the value at compile time and this value should not change throughout the execution of the program.

Thread-local storage

A thread, on the contrary, is a run-time concept. C++11 introduced the thread concept into the language, and thus you could say that a compiler can be "aware" of the thread concept. But, the compiler can't always predict if a thread is going to be executed (Maybe you run the thread only upon specific configuration), or how many instances are going to be spawn, etc.

Possible implementation

Instead of trying to enforce access to a specific module/method to a single thread using hacks and tricks, why not use a very primitive feature of the language?

You could just as well implement this using simple encapsulation. Just make sure that the only object that "sees" this method you are trying to protect is the thread object itself, for example:

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

using namespace std;

class SpecialWorker
{
public:
    void start()
    {
        m_thread = std::move(std::thread(&SpecialWorker::run, this));
    }

    void join()
    {
        m_thread.join();
    }

protected:
    virtual void run() { protectedTask(); }

private:
    void protectedTask()
    {
        cout << "PROTECT ME!" << endl;
    }

    std::thread m_thread;
};

int main(int argc, char ** argv)
{
    SpecialWorker a;
    a.start();
    a.join();

    return 0;
}

Please note that this example is lacking in error handling and is not production grade code! Make sure to refine it if you intend to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM