Listing 1: asynch macro derivatives

#ifndef THREAD_H
#define THREAD_H

// This class is the wrapper of a thread. It implements
// routines for manipulating a thread. It is the core of the
// asynch() macro and its derivatives
//
// NOTE: All the platform- and OS-specific functions are
//       encapsulated here. This is a sample implementation
//       for Windows platforms.
//
class Thread
{
public:
    Thread()
    {
        DWORD dwThreadID = 0;
        m_hThread = CreateThread(NULL, 0,
            (LPTHREAD_START_ROUTINE) threadProc,
            (PVOID) this, 0, &dwThreadID);
    }

    virtual ~Thread()
    {
        CloseHandle(m_hThread);
    }

    // The routine returns true if the thread is has finished, 
    // else it returns false when the thread is still running 
    // after the elapsed period.
    bool wait(int period = -1)
    {
        return WaitForSingleObject(m_hThread,
            period == -1 ? INFINITE : period) == WAIT_OBJECT_0;
    }

    bool terminate()
    {
        return TerminateThread(m_hThread, -1) == TRUE;
    }

    bool suspend()
    {
        return SuspendThread(m_hThread) == TRUE;
    }

    bool resume()
    {
        return ResumeThread(m_hThread) == TRUE;
    }

protected:
    virtual void run() = 0;

private:
    static void threadProc(Thread* thread)
    {
        thread->run();
    }

    HANDLE m_hThread;
};

// The asynchtX macros execute a statement in a new thread and
// return the thread object for further thread manipulation
#define asyncht0(statement, thread)\
{\
    class DummyThread: public Thread\
    {\
    protected:\
        virtual void\
        run(\
        )\
        {\
            statement;\
        }\
    };\
    thread = new DummyThread();\
}

#define asyncht1(statement, type1, param1, thread)\
{\
    class DummyThread: public Thread\
    {\
    public:\
        DummyThread(type1 param1):\
            param1(param1)\
        {\
        }\
    protected:\
        virtual void\
        run(\
        )\
        {\
            statement;\
        }\
    private:\
        type1                       param1;\
    };\
    thread = new DummyThread(param1);\
}

// define asynchtX in the same manner, e.g. asyncht3, asyncht4...

// The asynchX macros are the same as asynchtX() macros,
// but no thread object is returned. The delete this; statement
// is added to destruct the thread object and deallocate the
// memory used by the thread after the statement is executed.
#define asynch0(statement)\
{\
    Thread *thread;\
    asyncht0(statement; delete this;, thread);\
}

#define asynch1(statement, type1, param1)\
{\
    Thread *thread;\
    asyncht1(statement; delete this;, type1, param1, thread);
}\

// define asynchX in the same manner, e.g. asynch3, asynch4...

#endif THREAD_H
— End of Listing —