// testBoostLock.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include <vector>
using namespace std;
/*
Title:测试boost线程lock
Environment:VS2013Update3、boost 1.56
Tester:kagula
Date:2014-09-19
*/
int g_data = 0;
//ost::shared_mutex instance for multi read single write lock create!
boost::shared_mutex g_mutex;
//if you do not need single write multi read,etc only need exclusive lock
//you should reference boost::mutex and boost::lock_guard material!
void f_write(int id)
{
while (true)
{
{
//only one write
boost::unique_lock<boost::shared_mutex> lock(g_mutex);
cout << "f_write=>id=" << id << ",g_data=" << g_data++ << endl;
}
//if have any interrupt,break routine
boost::this_thread::interruption_point();
//wait one tenth second
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}//end for
}
void f_read(int id)
{
while (true)
{
//multi read
{
boost::shared_lock<boost::shared_mutex> lock(g_mutex);
cout << "f_read=>id=" << id << " ,g_data=" << g_data << endl;
}
//if have any interrupt,break routine
boost::this_thread::interruption_point();
//wait one tenth second
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}//end for
}
//test multi read single write
void testCase1()
{
vector<boost::thread> vecT;
const unsigned int count = 8;
//start threads
for (size_t i = 0; i < count; i++)
{
boost::thread t(f_write, i);
boost::thread t2(f_read, count+i);
vecT.push_back(boost::move(t));
vecT.push_back(boost::move(t2));
}
//wait a second
boost::detail::win32::Sleep(1000);
//interrupt threads
for (size_t i = 0; i < count*2; i++)
{
vecT[i].interrupt();
}
//wait until all threads stop
for (size_t i = 0; i < count * 2; i++)
{
vecT[i].join();
}
}//end func
//test try lock usage
void testCase2()
{
/*
notice:
below snippet will no block, only illustrate how to use
*/
boost::unique_lock<boost::shared_mutex> lock(g_mutex,boost::defer_lock);
if (lock.try_lock())
{
cout << "lock success, do something...." << endl;
//after get lock,you must unlock it for other one use!
lock.unlock();
}//end if
//lock twice boost will throw out a exception!
//if the statement can not get lock in a second ,will return false!
if (lock.timed_lock(boost::posix_time::milliseconds(1000)))
{
cout << "after get the lock, do something...." << endl;
//after get lock,you must unlock it for other one use!
lock.unlock();
}
}//end func
int _tmain(int argc, _TCHAR* argv[])
{
testCase1();
testCase2();
cout << "input any key to continue..." << endl;
cin.get();
return 0;
}