lundi 25 avril 2016

What does this thread_local RNG seed accomplish?

As part of an assignment, one of my professors gave me code that looks kind of like this:

namespace
{
  thread_local unsigned seed; // for use with rand_r

  void run_custom_tests() {
      // set this thread's seed
      seed = 0;

      // insert some random numbers into a map
      std::map<int, int> m;
      for (int i = 0; i < key_max; ++i)
          m.insert(i, rand_r(&seed));

      auto random_operations = [&]()
      {
          // do more stuff with rand_r(&seed)
      };

      std::thread t1(random_operations);
      std::thread t2(random_operations);
      t1.join();
      t2.join();
  }

} // end anonymous namespace

void test_driver()
{
    run_custom_tests();
}

My question is what is the purpose of that thread_local seed? I understand that you can't allow two threads to access the same global variable. But why not just make it local? Since seed is only used to fill that map and inside the lambda, and each thread has its own stack, wouldn't a local variable accomplish the same goal?

I did fine on the assignment, since the point wasn't to understand this usage of thread_local. But I'm still confused by this aspect of the program.




Aucun commentaire:

Enregistrer un commentaire