boost文件锁的使用

  boost中可以用boost::interprocess::file_lock类对文件进行加锁和解锁操作。

  

#include <fstream>
#include <iostream> 
#include <boost/interprocess/sync/file_lock.hpp> 
#include <cstdlib>

int main() 
{ 
  using namespace boost::interprocess; 
  std::string fileName("test"); 
  std::fstream file;

  file.open(fileName.c_str(), std::ios::out | std::ios::binary | 
      std::ios::trunc); 
  if (!file.is_open() || file.bad()) 
  {   
    std::cout << "Open failed" << std::endl; 
    exit(-1); 
  }
  std::cout << "Process 1 open file" << std::endl;

  try { 
    file_lock f_lock(fileName.c_str());
    f_lock.lock();
    std::cout << "Locked in Process 1" << std::endl;
    file.write("Process 1", 9); 
    file.flush(); 
    f_lock.unlock();
    std::cout << "Unlocked from Process 1" << std::endl;
  } catch (interprocess_exception& e) { 
    std::cout << e.what( ) << std::endl;
  }

  file.close();
  return 0;  
}

  为了避免作用域退出时,忘了解锁引发错误,可使用boost::interprocess::lock_guard。

lock_guard<file_lock>  guard(lock);
{
  // ....    
}
posted @ 2016-10-11 14:15  后端技术小屋  阅读(3197)  评论(0编辑  收藏  举报