Do I need a critical section to get the index of a value in a stringlist?

critical-section, delphi, multithreading

Solution

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.

Problem

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; ```

Original source