简体   繁体   中英

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!

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.

TIdTCPServer is a multi-threaded component. No matter what you wrap it in, the OnExecute event will always be triggered in the context of worker threads, one for each connected client, so any code you put inside the handler must be thread-safe. Members of the TMaster class need adequate protection from concurrent access by multiple threads at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM