Valhalla Legends Archive

Programming => General Programming => C/C++ Programming => Topic started by: Mephisto on October 17, 2004, 03:06 AM

Title: C++ Multi-Threading Class
Post by: Mephisto on October 17, 2004, 03:06 AM
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.
Title: Re: C++ Multi-Threading Class
Post by: K on October 17, 2004, 04:14 AM
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 (http://www.boost.org). boost threads (http://www.boost.org/libs/thread/doc/thread.html).


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();
}
Title: Re: C++ Multi-Threading Class
Post by: Maddox on November 05, 2004, 06:32 PM
CStupidClassName

java style members with hungarian notation.