I have a stringlist myStringList
with abouth 100 values and I'm doing asynchronous access to it.I would like to know if it is thread safe to do this :
currentIndex := myStringList.IndexOf(wantedValue);
or I always have to do this :
criticalS.Enter;
try
currentIndex := myStringList.IndexOf(wantedValue);
finally
criticalS.Leave;
end;
You absolutely do need to use a lock to protect all access of a mutable string list. If a writer thread modifies the list whilst your thread reads, the code can fail. You might refer to a string that has been destroyed. Or the list may be reallocated to a different address whilst you are reading it.
You need to use the same lock for all access, both read and write. You can use a multiple read, exclusive write lock rather than a critical section. But you do need synchronisation of some form.
If all threads are reading from the list, and no thread modifies it in any way, then you do not need a lock.
Here's a very nice thread-safe TStringList, which I've used very successfully.
TThreadStringList by Tilo Eckert http://www.swissdelphicenter.ch/torry/showcode.php?id=2167
It demonstrates the critical section technique very clearly.
If you do not manipulate with strings (add/insert/remove) from any other thread (meaning, data is there and it's static), there is no need for lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With