1 // Copyright (C) 2010 Vicente Botet 2 // 3 // Distributed under the Boost Software License, Version 1.0. (See accompanying 4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 5 6 #define BOOST_THREAD_VERSION 2 7 //#define BOOST_THREAD_PROVIDES_GENERIC_SHARED_MUTEX_ON_WIN 8 //#define BOOST_THREAD_USES_LOG 9 10 #include <boost/thread/thread_only.hpp> 11 #include <boost/thread/shared_mutex.hpp> 12 #include <boost/detail/no_exceptions_support.hpp> 13 //#include <boost/thread/detail/log.hpp> 14 15 boost::shared_mutex mutex; 16 thread()17void thread() 18 { 19 //BOOST_THREAD_LOG << "<thrd" << BOOST_THREAD_END_LOG; 20 BOOST_TRY 21 { 22 for (int i =0; i<10; ++i) 23 { 24 #ifndef BOOST_THREAD_USES_CHRONO 25 boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(50); 26 27 if (mutex.timed_lock(timeout)) 28 { 29 //BOOST_THREAD_LOG << "<thrd" << " i="<<i << BOOST_THREAD_END_LOG; 30 boost::this_thread::sleep(boost::posix_time::milliseconds(10)); 31 mutex.unlock(); 32 //BOOST_THREAD_LOG << "<thrd" << " i="<<i << BOOST_THREAD_END_LOG; 33 } 34 #else 35 boost::chrono::system_clock::time_point timeout = boost::chrono::system_clock::now() + boost::chrono::milliseconds(50); 36 37 //BOOST_THREAD_LOG << "<thrd" << " i="<<i << BOOST_THREAD_END_LOG; 38 if (mutex.try_lock_until(timeout)) 39 { 40 //BOOST_THREAD_LOG << "<thrd" << " i="<<i << BOOST_THREAD_END_LOG; 41 boost::this_thread::sleep_for(boost::chrono::milliseconds(10)); 42 mutex.unlock(); 43 //BOOST_THREAD_LOG << "<thrd" << " i="<<i << BOOST_THREAD_END_LOG; 44 } 45 #endif 46 } 47 } 48 BOOST_CATCH (boost::lock_error& ) 49 { 50 //BOOST_THREAD_LOG << "lock_error exception thrd>" << BOOST_THREAD_END_LOG; 51 } 52 BOOST_CATCH (...) 53 { 54 //BOOST_THREAD_LOG << "exception thrd>" << BOOST_THREAD_END_LOG; 55 } 56 BOOST_CATCH_END 57 //BOOST_THREAD_LOG << "thrd>" << BOOST_THREAD_END_LOG; 58 } 59 main()60int main() 61 { 62 //BOOST_THREAD_LOG << "<main" << BOOST_THREAD_END_LOG; 63 const int nrThreads = 20; 64 boost::thread* threads[nrThreads]; 65 66 for (int i = 0; i < nrThreads; ++i) 67 threads[i] = new boost::thread(&thread); 68 69 for (int i = 0; i < nrThreads; ++i) 70 { 71 threads[i]->join(); 72 //BOOST_THREAD_LOG << "main" << BOOST_THREAD_END_LOG; 73 delete threads[i]; 74 //BOOST_THREAD_LOG << "main" << BOOST_THREAD_END_LOG; 75 } 76 //BOOST_THREAD_LOG << "main>" << BOOST_THREAD_END_LOG; 77 return 0; 78 } 79