Lazarus

Free Pascal => Beginners => Topic started by: drallim33 on June 27, 2018, 01:37:25 am

Title: First time attempting multithreading
Post by: drallim33 on June 27, 2018, 01:37:25 am
Is this cheating? Exactly which level of hell will I be banished to for spamming these getters/setters in every class I declare?  :D

Code: Pascal  [Select][+][-]
  1. type
  2.   TMyProtectedInt = object
  3.   private
  4.     FTheInt : integer;
  5.     function GetTheInt: integer;
  6.     procedure SetTheInt(AValue: integer);
  7.   public
  8.     property Value : integer read GetTheInt write SetTheInt;
  9.   end;
  10.  
  11. var
  12.   AutoLock : TCriticalSection;
  13.  
  14. implementation
  15.  
  16. function TMyProtectedInt.GetTheInt: integer;
  17. begin
  18.   AutoLock.Acquire;
  19.   result := FTheInt;
  20.   AutoLock.Release;
  21. end;
  22.  
  23. procedure TMyProtectedInt.SetTheInt(AValue: integer);
  24. begin
  25.   AutoLock.Acquire;
  26.   FTheInt := AValue;
  27.   AutoLock.Release;
  28. end;
  29.  
  30. initialization
  31. AutoLock := TCriticalSection.Create;
  32.  
  33. finalization
  34. AutoLock.Free;
Title: Re: First time attempting multithreading
Post by: taazz on June 27, 2018, 02:53:21 am
Is this cheating? Exactly which level of hell will I be banished to for spamming these getters/setters in every class I declare?  :D

Code: Pascal  [Select][+][-]
  1. type
  2.   TMyProtectedInt = object
  3.   private
  4.     FTheInt : integer;
  5.     function GetTheInt: integer;
  6.     procedure SetTheInt(AValue: integer);
  7.   public
  8.     property Value : integer read GetTheInt write SetTheInt;
  9.   end;
  10.  
  11. var
  12.   AutoLock : TCriticalSection;
  13.  
  14. implementation
  15.  
  16. function TMyProtectedInt.GetTheInt: integer;
  17. begin
  18.   AutoLock.Acquire;
  19.   result := FTheInt;
  20.   AutoLock.Release;
  21. end;
  22.  
  23. procedure TMyProtectedInt.SetTheInt(AValue: integer);
  24. begin
  25.   AutoLock.Acquire;
  26.   FTheInt := AValue;
  27.   AutoLock.Release;
  28. end;
  29.  
  30. initialization
  31. AutoLock := TCriticalSection.Create;
  32.  
  33. finalization
  34. AutoLock.Free;
No, its not cheating its a bad way to serialize access to a single resource, mostly because autolock will lock all variables based on TMyProtectedInt not only the one you try to access, but you can easily solve that by moving the autolock variable in the private section of your class (making sure you create and destroy it with your class as well). Then you have the most basic protection scheme there is.
Title: Re: First time attempting multithreading
Post by: drallim33 on June 27, 2018, 03:58:23 am
Good to know
TinyPortal © 2005-2018