Boost読み書きロック
3154 ワード
//######### , ,
#include <boost/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/progress.hpp>
#include <boost/interprocess/detail/atomic.hpp>
#include <list>
#include <string>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <stdint.h>
#define THREAD_COUNT 100
typedef boost::mutex Uni_Mutex;
typedef boost::shared_mutex WR_Mutex;
typedef boost::unique_lock<WR_Mutex> writeLock;
typedef boost::shared_lock<WR_Mutex> readLock;
typedef boost::recursive_mutex Rcs_Mutex;
typedef boost::unique_lock<Rcs_Mutex> recuLock;
class Queue
{
public:
Queue(){};
~Queue(){};
void write(int value)
{
writeLock lockWrite(m_rwMutex);
m_list.push_back(value);
std::cout<<"write! now size is "<<size()<<" Thread id is "<<boost::this_thread::get_id()<<std::endl;
}
int read(int pos)
{
readLock lockRead(m_rwMutex);
if(size()==0 || pos>=size())
return -1;
std::list<int>::iterator itr = m_list.begin();
std::advance(itr , pos);
int value = *itr;
std::cout<<"read! now size is "<<size()<<" Thread id is "<<boost::this_thread::get_id()<<std::endl;
return value;
}
void remove(int pos)
{
writeLock lockWrite(m_rwMutex);
if(size()==0 || pos>=size())
return;
std::list<int>::iterator itr = m_list.begin();
std::advance(itr , pos);
m_list.erase(itr);
std::cout<<"remove! size is "<<size()<<" Thread id is "<<boost::this_thread::get_id()<<std::endl;
}
int size()
{
recuLock lock(m_sizeMutex);
return m_list.size();
}
private:
std::list<int> m_list;
Rcs_Mutex m_sizeMutex;
WR_Mutex m_rwMutex;
};
Queue queue;
volatile uint32_t count = 0;
typedef boost::shared_ptr<boost::thread> Thread;
Thread thread_array[THREAD_COUNT];
void increase_count()
{
boost::interprocess::detail::atomic_inc32(&count);
}
void testdata()
{
boost::this_thread::at_thread_exit(increase_count);
for(int i=0;i<10;i++)
{
queue.read(i);
if(i%4==0)
queue.write(i);
if(i%2==0)
queue.remove(i);
}
std::cout<<"Thread "<<boost::this_thread::get_id()<<" exit"<<std::endl;
}
int main(int argc , char* argv[])
{
boost::progress_timer t;
for(int i=0;i<10;i++)
queue.write(i);
std::cout<<"-----------thread create-----------"<<std::endl;
for(int i=0;i<THREAD_COUNT;++i)
{
thread_array[i].reset(new boost::thread(testdata));
}
while(1)
{
if(count>=THREAD_COUNT)
return 0;
}
}