Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2006-03-04 22:33:35


"Delfin Rojas" <drojas_at_[hidden]> writes:

>> Calderon Hector wrote:
>>
>> 1.- I don't see how to lock a file (fstream) for
>> reading/writing. Do I have to use OS functions?
>
> As far as I know there is no "lockable fstream" class in boost. You should
> be able to implement it yourself using a mutex. In other words, you can use
> the fstream as a shared resource and lock the mutex before each read and
> write. You may want to look into the iostreams library and create a
> thread_safe_iostream.

  boost::mutex io_mutex;

  struct synco
  {
      synco(std::ostream& os = std::cout) : os(os), lock(io_mutex) {}

      template <class T>
      std::ostream& operator<<(T const& x)
      {
          return os << x;
      }
      std::ostream& os;
      boost::mutex::scoped_lock lock;
  };

will allow you to do this:

     sync(std::cerr) << "hello" << std::endl << "world: " << 3.14159
       << std::endl;

And guarantee that it will all come out atomically, if all code
writing to cerr uses the same protocol.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net