Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 550
Viktor Anastasov Avatar asked May 31 '14 17:05

Viktor Anastasov


3 Answers

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.

like image 106
David Heffernan Avatar answered Nov 15 '22 08:11

David Heffernan


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.

like image 30
Chris Thornton Avatar answered Nov 15 '22 06:11

Chris Thornton


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.

like image 33
rsrx Avatar answered Nov 15 '22 07:11

rsrx