Boost logo

Boost Users :

Subject: Re: [Boost-users] [Thread] Strange problem.
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2011-04-04 10:06:27


On Mon, Apr 4, 2011 at 3:17 PM, Germán Diago <germandiago_at_[hidden]> wrote:

> Hello. I'm designing a class with a locking policy. I have some code
> that does exaclty this:
>
>
> if (cond) {
> locking_policy_.lock();
> out << message.message();
> locking_policy_.unlock();
> }
> return *this;
>
> And the lockingpolicy is a class like this one:
>
> struct ThreadSafe {
> boost::mutex io_mutex_;
> boost::unique_lock<boost::mutex> lock_;
>
> ThreadSafe() : io_mutex_(), lock_(io_mutex_, boost::defer_lock) {}
>
> void lock() {
> std::cout << "Locking from " << boost::this_thread::get_id()
> << std::endl;
> lock_.lock();
> }
>
> void unlock() {
> std::cout << "Unlocking from " <<
> boost::this_thread::get_id() << std::endl;
> lock_.unlock();
> }
> };
>
> Then, I create 3 threads and join them in the same order I created them:
>
> boost::thread t1(&doSomething, "Hello1", boost::ref(logsink));
> boost::thread t2(&doSomething, "Hello2", boost::ref(logsink));
> boost::thread t3(&doSomehting, "Hello3", boost::ref(logsink));
>
> t1.join();
> t2.join();
> t3.join();
>
> and I get a lock_error. Any help here, please? I can't figure out the
> problem.
>

Hi!

Could you please provide the doSomething implementation and how ThreadSafe
is used in the whole picture? Currently I don't understand the benefit of
lock_ being a member variable.

BTW: writing to std::cout from multpile threads without synchronisation will
produce "more or less" race conditions. Streams will still be in a
consistent state, but the output is anything else than expected. Most std
streams implementations are synchronized for single characters. Therefore
you might end up having the partial output from one thread and partial
output from other threads within a single line
.

With Kind Regards,
Ovanes



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