Search code examples
multithreadingdelphiindy

Delphi (Indy) Threadsafe classes


Let's say I have some class, TMaster, which asa field includes a TIdTCPServer. Some method of the TMaster class is responsible for the OnExecute event of the TIdTCPServer.

Firstly, is this threadsafe and acceptible? Secondly, let's assume my class has many other private fields (Name, Date, anything...) can the OnExecute event - which is really a method INSIDE the TMaster class, write to these variables safely?

I guess I mean to ask if private fields are threadsafe in this situation?

I am really new to threading and any help will be greatly appreciated!

Thanks, Adrian!


Solution

  • The way I approach this is not to have the fields used by the events belong to the TidTCPServer owner, but define a custom TidContext descendant and add the fields to that class.

    Then you simply set the ContextClass property on the server class to the type of the of your custom context. This way each Connection/Thread will get its own custom context containing its own private fields, this way there is no issue with concurrent thread access to the same fields.

    if you have a list of objects that need to be accessed by the different contexts you have two options.

    1) create copies the objects and store them in a private field in for each context instance This can be done in the OnConnect Event.

    2) Protect the objects from concurrent thread access using a synchroniser eg TIdCriticalSection, TMultiReadExclusiveWriteSynchronizer or semaphore,

    which method you use depends on each individual situation.

    if you need to manipulate any vcl components remember this can't safely be done outside the main vcl thread therefore you should create your own tidnotify decendants for this. performing this sort of operation using tidsynch can lead to deadlocks when stoping the tidtcpserver if it is in the middle of a vclsynch operation.

    this is just some of what I have learned over the course of a few years using Indy.