I am not all that familiar with threading. I have a question:

I am not all that familiar with threading. I have a question:
I have critical session in a thread and I call a function outside the
thread code. Do I have to have critical session there too? For example

...beginning of thread code...
CS.Acquire;
- some code -
i := GetIndex(AParam);
- some code -
CS.Release;
... end of thread...


function GetIndex(AParam: string): integer;
var
i: integer;
begin
// do I need CS.Acquire/Release here too?
//arrayName is global variable and is not being
//updated by any other thread
// other threads are calling this function as well
result := -1;
for i := 0 to High(arrayName) do
if AParam = arrayName[i] then
begin
result := i;
break;
end;
end;

Thanks.

Comments

  1. Zoran M No, I think the code is fine. You need, though, to add try-finally-end block for the CS.Release

    ReplyDelete
  2. If arrayName is never changed there is no need for CS, no matter from what thread GetIndex can be called.
    if arrayName can be changed from one thread and GetIndex can be called from this thread only, CS is unecessary too.
    if arrayname can be changed from one thread and GetIndex can be called from another thread, both GetIndex and array changing should be wrapped into CS for all threads.

    ReplyDelete

Post a Comment