Lock free multiple readers single writer

前端 未结 4 2000
既然无缘
既然无缘 2020-12-17 03:14

I have got an in memory data structure that is read by multiple threads and written by only one thread. Currently I am using a critical section to make this access threadsaf

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 03:48

    It's been a while since I got my hands dirty in Delphi, so verify this before using, but... from memory, you can get reference-counted behaviour if you use an interface and an implementation using TInterfacedObject.

    type
        IDataClass = interface
            function GetSome: integer;
            function GetData: double;
    
            property Some: integer read GetSome;
            property Data: double read GetData;
        end;
    
        TDataClass = class(TInterfacedObject, IDataClass)
        private
            FSome: integer;
            FData: double;
        protected
            function GetSome: integer;
            function GetData: double;
        public
            constructor Create(ASome: integer; AData: double);
        end;
    

    Then you make all your variables of type ISomeData instead (mixing ISomeData and TSomeData is a very bad idea... you easily get reference-counting problems).

    Basically this would cause the reference count to increment automatically in your reader code where it loads the local reference to the data, and it gets decremented when the variable leaves scope, at which point it would de-allocate there.

    I know it's a bit tedious to duplicate the API of your data class in an interface and a class implementation, but it is the easiest way to get your desired behaviour.

提交回复
热议问题