Boost - 多线程-boost recursive_mutex用法

#include <iostream>    
   
void run()  
{    
    for (int i = 0; i < 10; ++i)    
    {    
        std::cout << i << std::endl;    
    }    
}    
  
  
    
int main(int argc, char* argv[])    
{    
    boost::thread theard1(&run);    
    boost::thread theard2(&run);    
    boost::thread theard3(&run);   
    theard1.join();    
    theard2.join();    
    theard3.join();   
    return 0;    
} 

结果: 




00 


11 


22 


37 

48 

59 


37 










杂乱无章的,一个线程执行输出时被其他线程干扰. 

#include <boost/thread/thread.hpp>    
#include <boost/thread/recursive_mutex.hpp>  
#include <iostream>    
  
boost::recursive_mutex io_mutex;    
   
void run()  
{    
    boost::recursive_mutex::scoped_lock  lock(io_mutex);  
    for (int i = 0; i < 10; ++i)    
    {    
        std::cout << i << std::endl;    
    }    
}    
  
  
    
int main(int argc, char* argv[])    
{    
    boost::thread theard1(&run);    
    boost::thread theard2(&run);    
    boost::thread theard3(&run);   
    theard1.join();    
    theard2.join();    
    theard3.join();   
    return 0;    
}    

结果: 































当一个线程被Lock,其他线程只能等待. 
 

转自https://cooker.iteye.com/blog/748826

猜你喜欢

转载自blog.csdn.net/hanbing6174/article/details/86501965