Sunday, June 26, 2011

Using boost::thread as a drop-in replacement for pthreads (for Windows compatibility)

The problem:

You're a Posix programmer.  You code for proper, Unix-ish OSes.  People keep wanting Windows support, but you've used pthreads.

If you care, read on...



There exists a pthreads library for Windows, but good luck if you use 64-bit Windows...

The solution: Newer boost::thread libraries are usable as drop-in support!  Note: Use 1.45.0 or later - I found some interesting segfaults with 1.40 - if you get segfaults doing this, and valgrind tells you you're reading 4-8 bytes somewhere strange, upgrade your boost libraries.  Don't say I didn't warn you...


// In the header file:

#if USE_BOOST_THREADS
    boost::thread *ThreadObjects[MAX_SUPPORTED_THREADS];
    boost::mutex addCandidateHashMutexBoost;
#else
    pthread_t ThreadIds[MAX_SUPPORTED_THREADS];


    // Some mutexes...
    pthread_mutex_t addCandidateHashMutex;
    pthread_mutexattr_t addCandidateHashMutexAttr;
#endif


// In the C source:

    for(i = 0; i < this->ActiveThreadCount; i++) {
#if USE_BOOST_THREADS
        this->ThreadObjects[i] = new boost::thread(&CHHashTypeGPUThread, &this->ThreadData[i]);
#else
        pthread_create(&this->ThreadIds[i], NULL, CHHashTypeGPUThread, &this->ThreadData[i] );
#endif
    }
    // Wait for them to come back.
    for(i = 0; i < this->ActiveThreadCount; i++) {
#if USE_BOOST_THREADS
        this->ThreadObjects[i]->join();
#else
        pthread_join(this->ThreadIds[i], NULL);
#endif


// And, for your Mutexes, you can just do this;

#if USE_BOOST_THREADS
    this->addCandidateHashMutexBoost.lock();
#else
    pthread_mutex_lock(&this->addCandidateHashMutex);
#endif

// Do stuff
#if USE_BOOST_THREADS
    this->addCandidateHashMutexBoost.unlock();
#else
    pthread_mutex_unlock(&this->addCandidateHashMutex);
#endif



This should work nicely.  You can now pass arguments to the boost::thread object, and model pthreads closely enough.

I hadn't seen this documented anywhere else, so... enjoy! :)

No comments:

Post a Comment