Passing an Argument to a Thread Function - C++ boost

C++ examples for boost:thread

Description

Passing an Argument to a Thread Function

#include <iostream>
#include <string>
#include <functional>
#include <boost/thread/thread.hpp>

typedef void (*WorkerFunPtr)(const std::string&);

template<typename FunT, typename ParamT> 
struct Adapter {
   Adapter(FunT f, ParamT& p) : f_(f), p_(&p) {}   

   void operator()() { 
      f_(*p_);
   }
private:
   FunT    f_;
   ParamT* p_;  
};

void worker(const std::string& s) {
   std::cout << s << '\n';
}

int main() {

   std::string s1 = "This is the first thread!";
   std::string s2 = "This is the second thread!";

   boost::thread thr1(Adapter<WorkerFunPtr, std::string>(worker, s1));
   boost::thread thr2(Adapter<WorkerFunPtr, std::string>(worker, s2));

   thr1.join();
   thr2.join();
}

Related Tutorials