CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #1
    Join Date
    Jun 2010
    Posts
    4

    Run C++ class functions in thread

    I want to make a thread which will call functions of a class.
    I have changed the question with a simpler example to understand the problem:
    [/code]

    Suppose we have class rectangle
    Code:
    class CRectangle
    {
      int x, y;
      public:
    void set_values (int a,int b)
    {
      x = a;
      y = b;
    }
    
    void get_values (int &a,int &b)
    {
      a = x;
      b = y;
    }
    
        int area () {return (x*y);}
    };
    
    
    int main ()
    {
      int &x, &y;
      CRectangle rect;
    
      rect.set_values (3,4);
    
      rect.get_values (x,y);
      cout << "x = " << x << “y = ” << y;
    
      cout << "area: " << rect.area();
    
      return 0;
    }
    Here you see that we creating an object in main fn and depending on our need calling the various fns of the class.

    Now I want to make this class threadable in the sense I want to the class fns to be executed in a thread.
    So I wrote the following class:
    Code:
    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:
    Code:
    class CRectangle: public Thread
    {
      private:
        int x, y;
    void set_values (int a,int b)
    {
      x = a;
      y = b;
    }
    
    void get_values (int &a,int &b)
    {
      a = x;
      b = y;
    }
    
        int area () {return (x*y);}
    
    	public:
    		CRectangle () { }
    		~ CRectangle () { }
    
    		//the execute function, you need to override this one
    		void execute()
    {
    //Add your threaded code here
    }
    	
    };
    
    int main()
    {
    	CRectangle obj;
    
    	obj.start();
    	obj.stop();
    
    	return 0;
    }
    Now I want to know how to call ALL the various fns of class rectangle from within execute() in the same way as I called in main earlier.
    Last edited by [email protected]; October 23rd, 2011 at 02:51 PM. Reason: giving more simpler example to understand the problem

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured