I am writing an application where I am communicating with an SQL server, which provides an array of bytes in a blob field. I have a TObjectDictionary where I store objects, and each object stores the start byte and the number of bytes I need to read, and convert it to the required datatype.
The objects in the TObjectDictionary are referring to different SQL queries. So, to reduce the response time, my plan is to fire the queries at the same time, and whenever one of them finishes, it updates the global TObjectDictionary.
I know TObjectDictionary itself is not thread-safe, and if another thread would delete the object from the TObjectDictionary, I would have an issue, but this won't happen. Also, 2 or more threads won't be writing the same object.
At the moment I use TCriticalSection, so only 1 thread writes to objects in the dictionary, but I was wondering if this is really necessary?
1条答案
按热度按时间xmakbtuz1#
大多数RTL容器,包括TObjectDictionary,都不是线程安全的,并且需要足够的线程间序列化来避免问题。即使只是将对象添加到字典的行为也需要保护。TCriticalSection就足够了。
除非你在启动工作线程之前从主线程将所有对象添加到字典中,而工作线程只访问现有对象,不添加/删除对象,否则你不需要序列化对字典的访问。