#1 2014-08-22 14:24:24

CycleSoft
Member
Registered: 2013-01-18
Posts: 34

Thread-safe implementation of method-based services

As stated by SAD document  Rev. 1.18, page 283:

TSQLRestServerCallBack method-based services - i.e. published methods of the inherited
TSQLRestServer class as stated below (page 312) - must be implemented to be thread-safe by
default;

After doing some research (sadly I never worried about writing thread-safe code or not) I still have some doubt.

1) In general, to claim a pice of code is thread-safe, is it suffice avoid referencing 'global' variables?
Are 'local' variables 'safe' because are stack-allocated an thus each thread executing the code allocates his own 'copy' of local variables?

2) SAD documentation state also:

At RESTful / CRUD level,  Add/Update/Delete/TransactionBegin/Commit/Rollback methods are
locked by default (with a 2 seconds timeout), and  Retrieve* methods are not;
For example this implementation of a method-service:

does this mean that, if I nedd to access DB data in a method-service,  I don't have to care about thread-safety because the framework does it for me?


Considering this pseudo-implemetation of a method-service:

procedure TMyTSQLRestServerDBDescendant.MyMethod(Ctxt: TSQLRestServerURIContext);
var
  integervar: integer;
  stringvar: string;
  counter: integer;
begin

  try
    integervar := DoSomethingAndGetAValueForMyIntegerVar;
    stringvar := DoSomethingAndGetAValueForMyStringVar(integervar);
    // here I get a counter value from DB (an Ivoice counter, for example) and increment it
    // for later use, so it is VERY important that two concurrent threads have two different
    // values for the counter
    counter := GetCounterValueFromDBAndIncrementIt;
    DoStuffWithMyCounter(counter);
    Ctxt.Success;
  except
    on E: Exception do
      Ctxt.Error('Error: ' + E.Message, HTML_BADREQUEST);
  end;

end;

where obviously called procedures like DoSomethingAndGetAValueForMyIntegerVar don't reference any global variables, and GetCounterValueFromDBAndIncrementIt does not use any critical section or lock assuming the framework itself does (see 2) above).

does it seems thread-safe to your expert eyes? smile

Offline

#2 2014-08-22 14:33:31

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,183
Website

Re: Thread-safe implementation of method-based services

2) is true so your code sounds thread safe.

Offline

#3 2014-08-22 14:38:14

CycleSoft
Member
Registered: 2013-01-18
Posts: 34

Re: Thread-safe implementation of method-based services

Thanks Arnaud, your answers are always quick and useful!

Offline

Board footer

Powered by FluxBB