Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2007-11-26 03:00:19


v2cechura <v2cechura <at> atlas.cz> writes:
> I just recently installed and built boost library (1.34.1) using bcbboost. I
> wanted to try the boost::thread class. This simple code gives me "Access
> Violation" in Borland C++ Builder 2006 when boost::mutex is
> used:
>
> //--------------------------------------------------------------------------
> -
> #include <iostream>
> #include <boost/thread.hpp>
> //--------------------------------------------------------------------------
> -
> boost::xtime xt = {2};

Phil already pointed out the problem with this timeout.
 
> boost::mutex console; // line A
>
> void thr() // int n, boost::mutex & display {
> for (int i = 0; i < 10; i++)
> {
> {
> boost::mutex::scoped_lock l(console); // line B
> std::cout << "thr" << 1 << ":" << i << std::endl;
> }
> boost::thread::sleep(xt);
> } // end for
> }
>
> int main(int argc, char* argv[])
> {
> boost::thread_group tg;
> tg.create_thread(&thr);
>
> char c;
> std::cin >> c ;
> return 0;
> }

This thread will be detached if it has not finished when the closing brace of
main() is reached. In that case, it will be running concurrently with the
destructors of global objects, including the mutex "console", and the mutexes
internal to the thread library. If you access an object after (or during) its
destructor run, then you've got undefined behaviour.

Try adding "tg.join_all()" before the return.

> If line A and line B are commented-out then the error is gone.

That makes sense --- you're not accessing global state other than the iostreams,
so you're OK until the process exits.
 
Anthony


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk