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.
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.
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?