Showing posts with label thread. Show all posts
Showing posts with label thread. Show all posts

Sunday, August 12, 2012

C++ Thread Using Boost library sample

This post is the sample of essentials C++ thread using boost::threads library

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
#include <boost/bind.hpp>
#include "Elapsed.hpp"

const std::string RowRowRow("Row row row your boat gently down the stream");
const std::string Teapot("I'm a little teapot short and stout");

void sing(const std::string& lyrics,boost::posix_time::time_duration interval,bool indent=false) {
std::istringstream iss;
iss.str(lyrics);
std::string current;
do {
iss >> current;
if (iss) {
// extra spaces make it easier to read when interleaved by threading
if (indent)
std::cout << "\t\t";
std::cout  << current << "\n";
boost::this_thread::sleep( interval );
} // end if
} while ( !iss.bad() && !iss.eof() );
std::cout << "\n";
} // end sing()


class Singer {
std::string m_lyrics;
boost::posix_time::time_duration m_interval;
bool m_indent;
public:
Singer(const std::string& lyrics,boost::posix_time::time_duration interval,bool indent)
:
m_lyrics(lyrics),
m_interval(interval),
m_indent(indent)
{

} // end constructor
void perform() {
sing(m_lyrics,m_interval,m_indent);
} // end perform()
}; // end class Singer


int main(int argc,char* argv[]) {
using namespace boost::posix_time;


time_duration interval( milliseconds(250) );
auto delay( milliseconds(60) );

// "sing" with a function
sing( RowRowRow, interval );


// delay
boost::this_thread::sleep( delay );

// "sing" with a member function
Singer teapotSinger(Teapot,interval,true);
teapotSinger.perform();


return 0;
} // end main()

Reference

http://www.advancedcplusplus.com/5min-threads/

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;
}