Code snippets‎ > ‎C++‎ > ‎Boost‎ > ‎

Thread

Boost::Thread

Nice introduction into boost.thread:
http://www.ddj.com/cpp/184401518

Examples

These examples currenlty include Boost::Thread (shared_mutex) and Boost::extension
Examples using boost.
The examples are build using cmake.

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/bind.hpp>
#include <boost/timer.hpp>
 
boost::mutex io_mutex;
boost::shared_mutex sh_mutex;
 
void count(int id, bool use_shared_lock)
{
  for (int i = 0; i < 10; ++i)
  {
    if (false)
    { // Show debug information
      boost::unique_lock<boost::mutex>  lock(io_mutex);
      std::cout << id << ": " << i << std::endl;
    }
    if (use_shared_lock)
    {
      boost::shared_lock<boost::shared_mutex>  sh_lock(sh_mutex,boost::defer_lock);
      assert(!sh_lock.owns_lock());
      sh_lock.lock();
      assert(sh_lock.owns_lock());
      boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
      sh_lock.unlock();
    }
    else
    {
      boost::unique_lock<boost::shared_mutex>  lock(sh_mutex);
      boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
    }
  }
}
int main(int argc, char* argv[])
{
  {
    boost::timer t;
    boost::thread thrd1(boost::bind(&count, 1, false));
    boost::thread thrd2(boost::bind(&count, 2, false));
    boost::thread thrd3(boost::bind(&count, 3, false));
    thrd1.join();
    thrd2.join();
    thrd3.join();
    std::cout << "Unique lock took " << t.elapsed() << " seconds." << std::endl;
  }
  {
    boost::timer t;
    boost::thread thrd1(boost::bind(&count, 1, true));
    boost::thread thrd2(boost::bind(&count, 2, true));
    boost::thread thrd3(boost::bind(&count, 3, true));
    thrd1.join();
    thrd2.join();
    thrd3.join();
    std::cout << "Shared lock took " << t.elapsed() << " seconds." << std::endl;
  }
  boost::this_thread::sleep(boost::posix_time::seconds(2)); 
 
  return 0;
}

Code snippets

Boost sleep:


#include <boost/thread/thread.hpp>
 
boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 

Boost shared lock:


#include <boost/thread/shared_mutex.hpp>
boost::shared_mutex mutex;
 
{
  boost::shared_lock<boost::shared_mutex>  lock(mutex);
  ...
}


ċ
boost_examples.zip
(38k)
Nico Kruithof,
Aug 2, 2011, 2:56 AM
Comments