Thursday, August 18, 2011

MinGW std::thread fix

I talked earlier about a basic fix for MinGW enabling the use of std::thread and friends in MinGW. Since I will probably use them a lot, I wrote a small header file which does the work for you. It is available on github as a gist : https://gist.github.com/1154023

Since I believe people are too lazy to click links, and also because I want my blog to appear to have a lot of code in it, you will also find it just below:

/* Only use the code below if we have GCC with no support for GNU
 * threads 
 */
#if !defined(_GLIBCXX_HAS_GTHREADS) && defined(__GNUG__)

/* The boost thread library is used as a replacement for the
 * standard thread library. We'll consider it to be fully 
 * compatible with the missing library. See http://www.open-std.org/
 * ...jtc1/sc22/wg21/docs/papers/2008/n2497.html
 */

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>

/* Only classes are copied. Use boost directly or a real standard
 * library if you want free functions.
 */

namespace std {
  using boost::thread;
  
  using boost::mutex;
  using boost::timed_mutex;
  using boost::recursive_mutex;
  using boost::recursive_timed_mutex;
  
  using boost::lock_guard;
  using boost::unique_lock;
  
  using boost::condition_variable;
  using boost::condition_variable_any;
}

#endif /* Crippled GCC */

You may want to follow me on twitter.

1 comment:

  1. Note that boost has a slightly different interface to the C++11 thread facilities, and some features are missing. For example, if you wish to wait for a condition variable with a timeout then you might write

    std::condition_variable cv;
    std::mutex m;

    void foo(){
    std::unique_lock<std::mutex> ul(m);
    std::chrono::high_resolution_clock::time_point timeout=
    std::chrono::high_resolution_clock::now()+
    std::chrono::milliseconds(5);
    while(!done_waiting())
    if(cv.wait_for(ul,timeout)==
    std::cv_status::timeout)
    throw "timed out";
    }

    With boost, you cannot use std::chrono, as it doesn't work with boost.thread yet.

    Also, boost lacks std::async, and the equivalent to std::future is named boost::unique_future.

    For full support of C++11 threads with Mingw, you can purchase my Just::Thread library (http://www.stdthread.co.uk) which works with the TDM port of gcc 4.5.2.

    ReplyDelete