C++ thread library 본문

Programming/C++

C++ thread library

halatha 2011. 5. 25. 05:59
출처: http://yesarang.tistory.com/70

//	Runnable.h
#ifndef	_RUNNABLE_H
#define	_RUNNABLE_H

class Runnable	{
public:
	virtual void Run() = 0;
};

#endif

//	Thread.h
#ifndef	_THREAD_H
#define	_THREAD_H

#include "Runnable.h"

class Thread:	public Runnable	{
public:
	Thread();
	Thread(Runnable* pRunnable);
	void Start();
	void Wait();
	virtual void Run();

private:
	pthread_t	_thread;
	Runnable*	_runnable;

	static void* Main(void* pInst);
};

#endif

//	Thread.cpp
#include <iostream>
#include <pthread.h>
#include "Runnable.h"
#include "Thread.h"

using namespace	std;

Thread::Thread(): _thread(0), _runnable(0)	{
}

Thread::Thread(Runnable* pRunnable): _thread(0),_runnable(pRunnable)	{
}

void Thread::Start()	{
	cout << "Thread::Start() called" << endl;
	//	register Main() class method as pthred's callback
	int	nr	=	pthread_create(&_thread, NULL, &Thread::Main, this);
}

void Thread::Wait()	{
	cout << "Thread::Wait() called" << endl;
	void*	pData;
	int	nr	=	pthread_join(_thread, &pData);
}

void Thread::Run()	{
	if ( _runnable != 0 )	{
		cout << "Thread::Run(): calling runnable" << endl;
		_runnable->Run();
	}
}

void* Thread::Main(void* pInst)	{
	cout << "Thread::Main(): called" << endl;
	Thread*	pt	=	static_cast<Thread*>(pInst);
	pt->Run();
}

//	cppthread.cpp
#include <iostream>
#include <unistd.h>
#include "Runnable.h"
#include "Thread.h"

using namespace std;

class CountUpto: public Runnable	{
public:
	CountUpto(int n = 10): _count(n)	{}

	virtual void Run()	{
		cout << "CountUpto: Starts to run" << endl;
		int	i	=	1;
		do	{
			cout << "CountUpto::Run(): " << i++ << endl;
			sleep(1);
		}	while ( --_count);
	}

private:
	int	_count;
};

class TestThread:	public Thread	{
public:
	virtual void Run()	{
		cout << "TestThread::Run() called" << endl;

		int	i	=	5;
		do	{
			sleep(1);
			cout << "TestThread::Run(): " << i << endl;
		}	while ( --i );
	}
};

int main(void)
{
	Thread*	pt1	=	new TestThread();
	Thread*	pt2	=	new Thread(new CountUpto(20));

	pt1->Start(),	pt2->Start();
	pt1->Wait(),	pt2->Wait();
}

Comments