Return thread_local to main thread

I'm creating a coin-toss program where multiple coins are flipped using separate threads (one coin per thread) and the results are printed by the main thread. Because no thread (except the main) has any reason to care about any other thread, I was thinking of giving each thread a thread_local variable to keep track of the coin tosses.

I was thinking of setting up my worker threads like this:
-For each toss of the coin, calculate the percent that came back heads and place that in a thread_local variable.
-Once finished with the task, invoke a method on the main thread and pass the thread_local to the method.

Edit: Upon further research, I have found that threads also share the same heap. Therefore, I can perhaps pass a pointer to the above-mentioned thread_local to the method.
Last edited on
Thread-local storage only makes sense if you need to maintain some data across multiple stack frames but not across multiple threads. For example, the state of rand() is usually put in thread-local storage.
From what you've said, it sounds like your threads will nearly all their run-time inside your function, so you could simply use a normal local variable to keep track of toss frequencies.
Rather than having the thread function know where to store its result, why have one of its arguments be a reference to the place where it should store the result? Then the main program can tell each thread to store its result whereever it wants. See the increase_reference() example here: http://www.cplusplus.com/reference/thread/thread/thread/
> Rather than having the thread function know where to store its result
> why have one of its arguments be a reference to the place where it should store the result?

Keep it simple: a function should just return a double value rather than worry about where to store it.

1
2
3
4
5
6
7
8
9
10
double percent_heads( int num_flips )
{
    std::mt19937 rng( std::random_device{}() ) ;
    std::uniform_int_distribution<int> fair_coin( 0, 1 ) ;
    
    int cnt = 0 ;
    for( int i = 0 ; i < num_flips ; ++i ) cnt += fair_coin(rng) ;
    
    return num_flips > 0 ? cnt*100.0 / num_flips : 0 /* std::nan("1") */ ;
}

http://coliru.stacked-crooked.com/a/c2e356b826c3b075
Keep it simple: a function should just return a double value rather than worry about where to store it.

No argument here, but if he wants to run this in several different threads then how can he return the value to the main program? Don't thread routines return void?
> if he wants to run this in several different threads then how can he return the value to the main program?

Repeat: http://coliru.stacked-crooked.com/a/c2e356b826c3b075
Topic archived. No new replies allowed.