thread_2.cc

thread_2.cc
#include <iostream>
#include <thread>
#include <mutex>
 
using namespace::std;
 
// gcc -std=c++11 thread_1.cc -lstdc++ -o thread_1
 
std::mutex mu;
 
void shared_print(string msg,int id) {
  std::lock_guard<std::mutex> guard(mu);  // RAII - when guard goes out of scope
  //mu.lock();  // if cout throws an exception then the program will be locked forever.
  cout << msg << id << endl;  // still could mess up output if other process writes to cout. 
  //mu.unlock();
}
 
void fun1() {
 
  cout << "Im in function 1"<<endl;
}
class Fctor {
public:
  void operator()(string& msg) {
     for(int i=0;i>-10;i--)
        // cout << msg << i <<endl;
        shared_print(string(msg),i);
  }
};
 
int main(void)
{
  string s = "Message from main.";
  //std::thread t1((Fctor()),s);  // Parameters passed to a thread are always by value.
  std::thread t1((Fctor()),std::ref(s));
  // or you can use std::move(s)
  // transfer ownership of thread
  std::thread t2 = std::move(t1);
 
  // print out the ID
  cout << std::this_thread::get_id() << endl;
  cout << t2.get_id() <<endl;
 
  // Prevent Oversubscription - minimize context switching
  // std::thread::hardware_concurrency(); 
 
  try {
    for(int i=0;i<10;i++)
      // cout << "in main:"<<i<<endl;
      shared_print(string("In Main:"),i);
  } catch (...) {
    t2.join();
    throw;
  }
 
  t2.join();
}
Makefile
TARGETS=thread_1 thread_2
 
all: $(TARGETS)
 
% : %.cc
    gcc -std=c++11 $^ -lstdc++ -o $@
 
clean:
    rm $(TARGETS)