C++ MultiThreading

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Airslash
    New Member
    • Nov 2007
    • 221

    C++ MultiThreading

    Difficult subject, I know.

    Let's say I have the current pseudo class for a Thread in Windows:

    Code:
    class TThread
    {
    	private:
    	protected:
    		void __fastcall Execute();
    	public:
    		TThread(bool);
    		void ExitThread();
    		void StartThread();
    };
    This class has the ability to start a new thread and execute the code that's defined in the Execute method, or when expanded a bit executes the code stored in a function pointer. (not added)

    My question is now, I want to expand this class so that it has a internal boolean, and a getter + setter method for this boolean.
    What am I supposed to do fo the getter and setter functions, so they can be accessed by another thread for example.

    The idea is to have something like this:

    Code:
    class TThread
    {
    	private:
                    bool internalFlag;
    	protected:
    		void __fastcall Execute();
    	public:
    		TThread(bool);
    		void ExitThread();
    		void StartThread();
                    void SetInternalFlag(bool);
                    bool GetInternalFlag()
    };
    
    void __fastcall TThread::Execute()
    {
           while(true)
           {
                 // do stuff
                 if(internflag)
                 {
                     break;
                 }
            }
    }
    So I'm aiming at something to be able to stop my thread for example by playing with external threads and data members.

    Not really sure how to explain it better, but is this possible?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    To start with dont use internalflag directly even within the class always access via GetIntenalFlag and SetInternalFlag .

    Secondly the thing you are looking for is a CRITICALSECTION (google it). This is an object that prevents code from being executed by more than 1 thread at a time.

    Code:
        EnterCriticalSection(&cs);
    
        // Set/Get Flag
    
        ExitCriticalSection(&cs);
    Use a CRITICALSECTION object to protect access to your internal data so that only 1 thread at a time can access it.


    A Mutex does a similar thing but work inter-process, a CRITICALSECTION works intra-process but is also faster.

    If you are using .NET (or some other frameworks) they sometimes provide data types that automatically prevent themselves from access from more than 1 thread at a time so you could use one of those.

    Comment

    • Airslash
      New Member
      • Nov 2007
      • 221

      #3
      cheers for the fast reply, will definitly look into it.

      Comment

      Working...