0
votes

I am not sure whether what I am asking will have any impact or not. I am clearly a newbie in this stuff, but let us suppose I have an object:

TClientInfo = class(TObject)
   Username: TIdThreadSafeString;
   UserID: TIdThreadSafeInteger;
   Status: TIdThreadSafeInteger;
   Disconnected: TIdThreadSafeBoolean;
End;

I am using disconnected as a lock so if the client is disconnected from the server it will not do any operation on any of the fields of the object. Now lets suppose there are two functions which are simultaneously accessed by two threads: Thread1 and Thread2

function client_disconnected()
var Client: TClientInfo;
begin
  Client := FindClient(someusername);
  Client.Disconnected.Lock;
  Try
    Client.Disconnected.Value := True;
    Some operations......
  Finally
    Client.Disconnected.Unlock;
    FreeAndNil(Client.Disconnected);
    FreeAndNil(Client);
  End;
end;

The disconnect routine to lock the the disconnected variable sets its value to true and performs the operations, in the end it frees up the disconnected variable and also the object (leave the other variables).

Now there is this other function:

function someoperations()
Var Client: TClientInfo;
begin
  Client := FindClient(somename);
  Client.Disconnected.Lock;
  Try
    If Client.Disconnected.Value = True Then Exit;
    some operations.....
  Finally
    Client.Disconnected.Unlock;
  End;
end;

Now the two threads are accessing both the functions at same time, the client got disconnected, Thread1 locked the disconnected variable, while the Thread2 is trying to lock the disconnected variable for operations while it waits for the disconnection routine to be executed and the disconnected variable is unlocked. Now at the same time Thread1 tries to free the object and its variables and Thread2 is accessing the variables of that object.

What will happen? Will it cause an exception or am I just assuming things (sorry i've been banging my head with all the exceptions occurring in my server applications). If yes, then what will be the safest way to free the object?

Thanks

1

1 Answers

0
votes

Don't let this happen - do what TCP does.

Do not free Client objects just because they are disconnected. Put them in a 'FreePending' delta-queue and only free them after, say a minute. By that time, any other thread/s that may have a reference to the disconnected client object up will have noticed the disconnected state and abandoned their operations.