Can a thread_local C ++ 11 variable inherit its initial value from a parent thread?

I would like to have a variable thread_localto change the logging level applied in each thread of my application. Something like that:

enum class trace_level { none, error, warning, log, debug, verbose };
static thread_local trace_level min_level = trace_level::log;

The default value should be trace_level::logfor the main thread when the application starts, but if it was changed before other threads started, I would like the child threads to start from the current parent value.

Is there a way to do this with a variable thread_local? Since this code is buried in the library, it is not possible to simply set the value manually at the beginning of each stream.

+4
source share
2

, . , " " - " odr". , , , , ( , - - ), , ), , , .

:

#include <stdio.h>

#include <chrono>
#include <functional>
#include <thread>
#include <string>

using std::string;

enum class trace_level { none, error, warning, log, debug, verbose };

trace_level log_level = trace_level::log;


static thread_local trace_level min_level = log_level;
void f(string const& s)
{

    printf("%s, min_level == %d\n", s.c_str(), (int) min_level);
}



int main()
{
    std::thread t1{std::bind(f,"thread 1")};

    //TODO: std::this_thread::sleep_for(std::chrono::milliseconds(50));

    log_level = trace_level::verbose;
    std::thread t2{std::bind(f,"thread 2")};

    t1.join();
    t2.join();
}

sleep_for() , , ():

C:\so-test>test
thread 1, min_level  == 5
thread 2, min_level  == 5

, sleep_for() , ( - ):

C:\so-test>test
thread 1, min_level  == 3
thread 2, min_level  == 5

, , , , , , , .

- . log_level, undefined. , , , . log_level :

std::atomic<trace_level> log_level(trace_level::log);

:

3.6.2 [basic.start.init]

... ....

3.7.2/2 [basic.stc.thread]

odr (3.2) , , .

+1

.

thread_local trace_level min_level = trace_level::log;
trace_level *min_level_ptr = nullptr;

:

if (!min_level_ptr)
    min_level_ptr = &min_level;
else
    min_level = *min_level_ptr;

(, min_level_ptr ).

: , min_level , . min_level_ptr, , , , . "" , min_level. .

+1

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


All Articles