#include "read_write_mutex.hpp" #include #include #include #include #include #include #include "highprecisiontime.hpp" unsigned const n = 100000; unsigned const vec_len = 10; unsigned const n_readers = 15; unsigned const n_upgradables = 5; unsigned const n_writers = 5; #define RU 1 #define WW 2 #define RW 3 #define SL 4 #define MODE RU boost::read_write_mutex mtx=BOOST_RW_MUTEX_INIT; boost::read_write_mutex cout_mut=BOOST_RW_MUTEX_INIT; std::vector v(vec_len); void clearscr() { // std::cerr << "\033[2J"; } void gotoxy(int row, int col) { COORD pos={ col,row }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); } unsigned __stdcall reader_thread(void* idp) { int id=(int)idp; for( unsigned i = 0; i < n; ++i ) { if ((i+1) % (n/100) == 0) { boost::write_lock lock(cout_mut); gotoxy(id, 0); std::cerr << "read thread "<< id << " at " << (float)(i+1)/n * 100 << '%'; gotoxy(30,0); } #if MODE == WW boost::write_lock lock(mtx); #else boost::read_lock lock(mtx); #endif int m = v.front(); for (std::vector::const_iterator i = v.begin(), e = v.end(); i < e; ++i) { assert(*i == m); } } return 0; } unsigned __stdcall writer_thread(void* idp) { int id=(int)idp; for( unsigned i = 0; i < n; ++i ) { if ((i+1) % (n/100) == 0) { boost::write_lock lock(cout_mut); gotoxy(id, 0); std::cerr << "writ thread "<< id << " at " << (float)(i+1)/n * 100 << '%'; gotoxy(30,0); } boost::write_lock lock(mtx); int m = v.front(); for (std::vector::iterator i = v.begin(), e = v.end(); i < e; ++i) { *i += 1; assert(*i == m+1); } } return 0; } unsigned __stdcall upgradable_thread(void* idp) { int id=(int)idp; for( unsigned i = 0; i < n; ++i ) { if ((i+1) % (n/100) == 0) { boost::write_lock lock(cout_mut); gotoxy(id, 0); std::cerr << "upgr thread "<< id << " at " << (float)(i+1)/n * 100 << '%'; gotoxy(30,0); } #if MODE == RU boost::upgradeable_lock lock(mtx); #else boost::write_lock lock(mtx); #endif int m = v.front(); for (std::vector::const_iterator it = v.begin(), e = v.end(); it < e; ++it) { assert(*it == m); } if (i % 10 == 0) { #if MODE == RU boost::write_lock wlock(lock); #endif for (std::vector::iterator i = v.begin(), e = v.end(); i < e; ++i) { *i += 1; assert(*i == m+1); } } } return 0; } int main() { clearscr(); std::vector tg; int id = 0; HighPrecisionTime start=HighPrecisionTime::now(); for( int i = 0; i < n_writers; ++i ) tg.push_back((void*)_beginthreadex(NULL,0,writer_thread,(void*)++id,0,NULL)); for( int i = 0; i < n_readers; ++i ) tg.push_back((void*)_beginthreadex(NULL,0,reader_thread,(void*)++id,0,NULL)); for( int i = 0; i < n_upgradables; ++i ) tg.push_back((void*)_beginthreadex(NULL,0,upgradable_thread,(void*)++id,0,NULL)); for(unsigned i=0;i