Saturday, August 4, 2012

Thread samples

C++11 Standard thread sample using std::thread


#include <iostream>
#include <thread>

void thFun(int i) {
  std::cout << "Worker " << i << "!\n";
}

int main() {
  // Create a thread
  std::thread th(&thFun); // pass fun to thread constructor
  std::cout << "Main Thread!\n";
 
  // Need to wait until the worker thread finish the job
  // This by calling join();
  th.join();
 
  return 0;
}

Multiple forks


// Sample of Thread multiple forks
#include <iostream>
#include <thread>
#include <algorithm> // for_each
#include <cassert>

void thFun(int i) {
  std::cout << "Worker " << i << "!\n";
}

int main() {
  // Create store to store the created threads
  std::vector<std::thread> workers;
 
  for (int i = 0; i < 10; ++i) {
    auto th = std::thread(&thfun, i);
    // Every thread push back into the store of the stack
    workers.push_back(std::move(th));
    assert(!th.joinable());
  }

  std::cout << "Main Thread!\n";
  std::for_each(workers.begin(), workers.end(), [](std::thread & th)) {
    assert(th.joinable());
    th.join();
  });
  return 0;
}

No comments:

Post a Comment