How to create an array of thread objects in C++11?

前端 未结 2 417
[愿得一人]
[愿得一人] 2021-02-01 16:21

I want to learn how to create multiple threads with the new C++ standard library and store their handles into an array.
How can I start a thread?
The examples that I saw

相关标签:
2条回答
  • 2021-02-01 16:37

    Nothing fancy required; just use assignment. Inside your loop, write

    myThreads[i] = std::thread(exec, i);
    

    and it should work.

    0 讨论(0)
  • 2021-02-01 16:50

    With C++0x / C++11, try using vectors instead of arrays of threads; something like this:

    vector<thread> mythreads;
    int i = 0;
    for (i = 0; i < 8; i++)
    {
       mythreads.push_back(dostuff, withstuff);
    }
    auto originalthread = mythreads.begin();
    //Do other stuff here.
    while (originalthread != mythreads.end())
    {
       originalthread->join();
       originalthread++;
    }
    

    Edit: If you really want to handle memory allocation yourself and use an array of pointers (i.e. vectors just aren't your thing) then I can't recommend valgrind highly enough. It has memory allocation checkers and thread checkers, etc, etc. Priceless for this kind of thing. In any case, here's an example program using an array of manually allocated threads, and it cleans up after itself (no memory leaks):

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <cstdlib>
    
    // globals are bad, ok?
    std::mutex mymutex;
    
    
    int pfunc()
    {
      int * i = new int;
      *i = std::rand() % 10 + 1;
    
      // cout is a stream and threads will jumble together as they actually can
      // all output at the same time. So we'll just lock to access a shared
      // resource.
      std::thread::id * myid = new std::thread::id;
      *myid = std::this_thread::get_id();
      mymutex.lock();
      std::cout << "Hi.\n";
      std::cout << "I'm threadID " << *myid << std::endl;
      std::cout << "i is " << *i << ".\n";
      std::cout << "Bye now.\n";
      mymutex.unlock();
    
      // Now we'll sleep in the thread, then return.
      sleep(*i);
      // clean up after ourselves.
      delete i;
      delete myid;
      return(0);
    }
    
    
    int main ()
    {
    
      std::thread * threadpointer = new std::thread[4];
      // This seed will give us 5, 6, 4, and 8 second sleeps...
      std::srand(11);
      for (int i = 0; i < 4; i++)
        {
          threadpointer[i] = std::thread(pfunc);
        }
      for (int i = 0; i < 4; i++)
          // Join will block our main thread, and so the program won't exit until
          // everyone comes home.
        {
          threadpointer[i].join();
        }
      delete [] threadpointer;
    }
    
    0 讨论(0)
提交回复
热议问题