Boost logo

Boost Users :

From: gunnarnl (gunnar_at_[hidden])
Date: 2002-03-20 16:17:40


After overcoming my initial problems with compiling I have another
question. I like very much the thread_group concept. My idea is to
create different groups running different type of tasks. E.g. one
group deals with user request tasks and another deal with responses
from a mainframe etc. In addition, I think it would be good to be
able to maximize the number of threads running concurrently in a
single group. In this way one could tune the processes regarding to
the number of CPUs and so that not one single group gets more CPU
usage than others etc. I guess I'm not the first one to think about
these things. Does anyone have any ideas about these type of task
groups?
 
Although it doesn't nearly contain what I want to do, I got the
following test work nicely.

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

template<class T>
class thread_task
{
public:
        thread_task(T* obj) : m_obj(obj)
        {
                assert(m_obj != 0);
        }
        virtual ~thread_task() { }
        void operator() ()
        {
                m_obj->setup();
                m_obj->run();
                m_obj->cleanup();

                delete m_obj;
        }
private:
        T* m_obj;
};

class my_task
{
public:
        my_task() {}
        void setup()
        {
                std::cout << "setup " << GetCurrentThreadId() <<
std::endl;
        }
        void run()
        {
                std::cout << "Start sleeping in thread " <<
GetCurrentThreadId() << std::endl;
                boost::xtime xt;
                boost::xtime_get(&xt, boost::TIME_UTC);
                xt.sec += 1;

                boost::thread::sleep(xt);
                std::cout << "Woke up " << GetCurrentThreadId() <<
std::endl;

        }
        void cleanup()
        {
                std::cout << "cleanup " << GetCurrentThreadId() <<
std::endl;
        }
};

int main(int argc, char* argv[])
{

        boost::thread_group threads;
        int i;
         for (i = 0; i < 10; ++i)
        {
                my_task* aTask = new my_task();
                thread_task<my_task> new_task(aTask);
                threads.create_thread(new_task);
        }
        threads.join_all();

        return 0;
}

By the way, is there an operation in boost::thread to get the current
thread id?


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net