samedi 8 août 2020

How to fix this C++ thread global declaration/definition?

This is my simple C++ code.

When I compile in Linux, I get this error only for t_vec_g variable. I do not understand this error. I want to have threal_local storage with global scope with in the thread.

Why are t_in_g and t_vec_l are correct and t_vec_g is error?

$ g++ -std=c++11 test.cpp

test.cpp:6:41: error: non-local variable ‘t_vec_g’ declared ‘__thread’ needs dynamic initialization static __thread vector<int> t_vec_g(10,3);

test.cpp:6:29: note: C++11 ‘thread_local’ allows dynamic initialization and destruction
 static __thread vector<int> t_vec_g(10,3);
#include <iostream>
#include <vector>

using namespace std;

static __thread vector<int> t_vec_g(10,100);
static __thread int t_in_g = 200;

main(int agrc, char *argv[], char *envp[])
{

        static __thread vector<int> t_vec_l(10,300);
        static __thread int t_in_l = 400;

        cout << t_in_l << endl;
        cout << t_vec_l[0] << endl;
        cout << t_in_g << endl;
        cout << t_vec_g[0] << endl;
}

Aucun commentaire:

Enregistrer un commentaire