• Welcome to Valhalla Legends Archive.
 

C++ Multi-Threading Class

Started by Mephisto, October 17, 2004, 03:06 AM

Previous topic - Next topic

Mephisto

I'm new to writing multi-threaded applications and just started with the necesity of having to use multiple threads.  So anyways, I created a simple class to make things more simplified and easiser to reuse code that is often repeated.  The class can be found here: http://www.madzlair.net/mephisto/Documents/CThreadClass.cpp.

Question: What can be done to improve this class based on the knowledge of experienced users with multi-threading, and whether it seems like this class will even work or not.  I did test it, and it worked with my tests, though I'm not 100% whether the Mutex support works or not.

K

#1
This may not be exactly what you want to hear, but my mantra is to never reinvent the wheel.  Once again I'm pimping boost. boost threads.


example code shamelessly stolen from the boost docs:
comments are mine.


// Copyright (C) 2001-2003
// William E. Kempf
// [blah blah copyright whatever]

#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>

// function object to pass to thread
struct thread_alarm
{
    thread_alarm(int secs) : m_secs(secs) { }

    // the operator() is called by the thread when it begins execution.
    // when this function ends, the thread is terminated
    void operator()()
    {
        // hookup a delay
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += m_secs;

        boost::thread::sleep(xt);

        std::cout << "alarm sounded..." << std::endl;
    }

    int m_secs;
};

int main(int argc, char* argv[])
{
    int secs = 5;
    std::cout << "setting alarm for 5 seconds..." << std::endl;
    thread_alarm alarm(secs);
    boost::thread thrd(alarm);

    // block until thrd exits.
    thrd.join();
}

Maddox

CStupidClassName

java style members with hungarian notation.
asdf.