How can I handle variable accessing (read and write) simultaneously in a multithreaded application ?

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can do this with a Mutex ... In delphi terms, a TCriticalSection will take care of this.

You should NEVER try to access variables simultaneously (specially for write) ... its certain that your app will crash sooner rather than later.  By using a TCriticalSection you  protect each variable so that only one threat can access it at a time.  As soon as you finish updating the variable (writing to it) you should call TCriticalSection.leave.  At that point, another thread will enter the critical section and so on.   ... for example


  someclass = class
    CriticalSection: TCriticalSection;
   constructor create;
  destructor destroy;
    procedure SomeClass.bcISAPIFilterException(Sender: TObject; E: Exception);

constructor create;
  CriticalSection:= TCriticalSection.Create;

destructor destroy;

 procedure SomeClass.bcISAPIFilterException(Sender: TObject; E: Exception);
  CriticalSection.Enter; //protect the log file from multiple threads
  bcLog.LogInfo('An exception occured: ' + E.Message);

Read the delphi documentation on TCriticalSection as it will explain to you exactly what its used for and why is it needed.

You can also search google for "pthread Mutex" and that will explain in more detail what mutexes (TCriticalSections) are used for.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Simple variables are not a problem. Records, strings, objects, lists, arrays etc are a problem. Several objects have a thread-safe version, such as a Lock/Unlock method. TThreadList is a thread-safe version of TList which does not explicitly need to be locked/unlocked.

Failing that, if the data is more complex, use a CriticalSection as jconde suggests.

Geoff M.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.