1 Replies - 493 Views - Last Post: 20 October 2011 - 10:02 PM Rate Topic: -----

#1 rupeshkp728@gmail.com  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 20-October 11

Run C++ class functions in thread

Posted 20 October 2011 - 09:48 PM

I want to make a thread which will call functions of a class.
I have a doubt about the thread class fn.
I have seen that at many places a class which is to be made threadable is derived from a thread class as shown below:

class Thread
{
	Thread *threadptr;
	HANDLE    ThreadHandle;
 
	public:
		Thread()
		{
			Thread = 0;
		}
 
		void start()
		{
			DWORD threadID;
 
			threadptr = this;
			ThreadHandle = CreateThread(0, 0, entrypoint, threadptr, 0, &threadID);
		}
 
		void stop()
		{
			
		CloseHandle (ThreadHandle, 0);
		}
 
 		static unsigned long entrypoint(void* ptr)
		{
			((Thread*)ptr)->execute();
			return 0;
		}
		virtual void execute() = 0;
};



Usage of thread class:
class ThreadUsage: public Thread
{
	public:
		ThreadUsage () { }
		~ ThreadUsage () { }
 
		//the execute function, you need to override this one
		void execute()
{
//Add your threaded code here
}
	
		void fn1();
		void fn2();
		void fn3();
};
 
int main()
{
	ThreadUsage obj;
 
	obj.start();
	obj.stop();
 
	return 0;
} 



In the thread only the derived class function execute() will get called.
Now in this example my question is if we have many more functions in derived class like above we have 3 more fns. fn1(), fn2() and fn3() then how can we call these other functions in thread?

Is This A Good Question/Topic? 0
  • +

Replies To: Run C++ class functions in thread

#2 Hezekiah  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 207
  • View blog
  • Posts: 550
  • Joined: 12-July 09

Re: Run C++ class functions in thread

Posted 20 October 2011 - 10:02 PM

If you want to call the functions from the new thread, just call them in the execute() function. If you want to call them from the main thread, use e.g. obj.fn1() in main().
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1