简体   繁体   English

C ++ constexpr thread_local ID

[英]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变量中获得不同的值?

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. 似乎constexpr thread_local受支持,但在这种情况下thread_local指示符似乎没有任何作用。

If you think about your question, you yourself can see why this is not possible. 如果您考虑自己的问题,您自己会明白为什么这不可能。

What is constexpr ? 什么是constexpr

According to the informal standard site cppreference : 根据非正式标准网站cppreference

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time . constexpr说明符声明可以在编译时评估函数或变量的值。

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. C ++ 11在语言中引入了线程概念,因此您可以说编译器可以“意识到”线程概念。 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. 如果要使用它,请确保对其进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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