Search code examples
c++boost-threadboost-interprocess

boost interprocess scoped lock with timer blocks despite should return


I have some code of my application that makes usage of boost inteprocess scoped lock with timers. When a mutex is acquired in one thread, a second thread tyring to acquire it for few milliseconds will fail and will log something to screeen.

I don't know why but with the version of boost 1.50 this doens't work anymore. The code below I can see that the thread #2 doesn't print "ERROR" but is completely stuck.

Am I missing something here?

I am using LINUX kernel 2.6.32 with g++.

COuld it be something to deal with UTC? I read o boost that the time used by such lock is UTC and in date time I am reading right now about local_adjustor and conversion from local to utc and vice-versa.

AFG

   #include <iostream>
   #include <boost/interprocess/sync/scoped_lock.hpp>
   #include <boost/date_time/posix_time/posix_time.hpp>
   #include <boost/interprocess/sync/named_mutex.hpp>
   #include <boost/thread.hpp>
   #include <boost/bind.hpp>

   namespace bi = boost::interprocess;


   void  lock_test( bi::named_mutex& mt, bool long_sleep ) { 

           boost::posix_time::ptime pt = 
             boost::posix_time::microsec_clock::local_time()
             +  boost::posix_time::milliseconds(100);

            bi::scoped_lock<bi::named_mutex> l( mt, pt );
            if( l.owns() ){
            std::cout << "Locked"<<std::endl;
            }
            else{
            std::cout << "ERROR" << std::endl;
            std::cout.flush();
            return ;
            }

            if(long_sleep){
                while(true) {sleep(1);std::cout<<"[]";std::cout.flush();}
            }
        }

        int main(){

               bi::named_mutex  m_mutex( bi::open_or_create, "ciao"
               , bi::permissions( 0666  ));
               boost::thread t1 = boost::thread( &lock_test
               , boost::ref( m_mutex), true );
               sleep(4);
               boost::thread t2 = boost::thread(  &lock_test
               , boost::ref(m_mutex), false );
               while(true){sleep(1);}
        }

Solution

  • It looks that if I switch from boost::posix_time::microsec_clock::local_time() to

     boost::posix_time::microsec_clock::universal_time() 
    

    everything works fine.