sysuthrd.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2005,2009 by the Free Pascal development team
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. {$ifdef FPC_HAS_FEATURE_THREADING}
  11. constructor TSimpleRWSync.Create;
  12. begin
  13. System.InitCriticalSection(Crit);
  14. end;
  15. destructor TSimpleRWSync.Destroy;
  16. begin
  17. System.DoneCriticalSection(Crit);
  18. end;
  19. function TSimpleRWSync.Beginwrite : boolean;
  20. begin
  21. System.EnterCriticalSection(Crit);
  22. result:=true;
  23. end;
  24. procedure TSimpleRWSync.Endwrite;
  25. begin
  26. System.LeaveCriticalSection(Crit);
  27. end;
  28. procedure TSimpleRWSync.Beginread;
  29. begin
  30. System.EnterCriticalSection(Crit);
  31. end;
  32. procedure TSimpleRWSync.Endread;
  33. begin
  34. System.LeaveCriticalSection(Crit);
  35. end;
  36. type
  37. PMREWThreadInfo = ^TMREWThreadInfo;
  38. TMREWThreadInfo = record
  39. Next: PMREWThreadInfo;
  40. Active: longint;
  41. RefCount: LongInt;
  42. ThreadID: TThreadID;
  43. end;
  44. const
  45. cInUse: LongInt = MaxInt;
  46. cAvail: LongInt = 0;
  47. const
  48. cNewReader : LongInt = - $1;
  49. cNewWriter : LongInt = $10000;
  50. cReadMask : LongInt = $0000FFFF;
  51. cWriteMask : LongInt = $7FFF0000;
  52. constructor TMultiReadExclusiveWriteSynchronizer.Create;
  53. begin
  54. System.InitCriticalSection(fwritelock);
  55. fwaitingwriterlock:=RTLEventCreate;
  56. RTLEventResetEvent(fwaitingwriterlock);
  57. fwriterequests:=0;
  58. factivethreads:=0;
  59. freaderqueue:=BasicEventCreate(nil,true,false,'');
  60. { synchronize initialization with later reads/writes }
  61. ReadWriteBarrier;
  62. end;
  63. destructor TMultiReadExclusiveWriteSynchronizer.Destroy;
  64. var
  65. p,q: PMREWThreadInfo;
  66. i: integer;
  67. begin
  68. System.DoneCriticalSection(fwritelock);
  69. RtlEventDestroy(fwaitingwriterlock);
  70. BasicEventDestroy(freaderqueue);
  71. { Clean up thread info }
  72. for i:=Low(fThreadList) to High(fThreadList) do
  73. begin
  74. q:=fThreadList[i];
  75. fThreadList[i]:=nil;
  76. while q<>nil do
  77. begin
  78. p:=q;
  79. q:=q^.Next;
  80. FreeMem(p);
  81. end;
  82. end;
  83. end;
  84. function TMultiReadExclusiveWriteSynchronizer.Beginwrite : boolean;
  85. var
  86. p: PMREWThreadInfo;
  87. begin
  88. { Result indicates whether the protected memory was not modified,
  89. that is, it is set to false if another writer could have chagned
  90. memory}
  91. Result:=True;
  92. { for quick checking by candidate-readers -- use interlockedincrement/
  93. decrement instead of setting 1/0, because a single thread can
  94. recursively acquire the write lock multiple times }
  95. { Count pending not granted requests so writes always take priority over
  96. read requests}
  97. System.InterlockedIncrement(fwriterequests);
  98. { Get per thread counter }
  99. p:=PMREWThreadInfo( GetThreadInfo(True) );
  100. if System.TryEnterCriticalSection(fwritelock)=0 then
  101. begin
  102. { TryEnterCriticalSection failed, so not first in the write lock queue }
  103. Result:=False;
  104. { If we hold a read lock, then a deadlock will result.. This is because
  105. the first thread in the write queue (holding fwritelock) does not have
  106. mutexes write lock, as it must be waiting on this thread to release
  107. its' read lock }
  108. if p^.RefCount > 0 then
  109. begin
  110. System.InterlockedDecrement(fwriterequests);
  111. raise TMREWException.Create('Deadlock detected');
  112. end;
  113. { wait for any other writers that may be in progress }
  114. System.EnterCriticalSection(fwritelock);
  115. end;
  116. { Need to synchronize with readers only when this is the first
  117. write request by this thread }
  118. if (p^.RefCount and cWriteMask)=0 then
  119. begin
  120. { Count active threads rather than readers. A write request can
  121. be granted whenever the count has reduced to one }
  122. { no order vs increment of fwriterequests needed, because we acquired
  123. a critical section which orders for us }
  124. if p^.RefCount=0 then
  125. System.InterlockedIncrement(factivethreads);
  126. { new readers have to block from now on; writers get priority to avoid
  127. writer starvation (since they have to compete with potentially many
  128. concurrent readers and other writers) }
  129. BasicEventResetEvent(freaderqueue);
  130. { it is possible that earlier on we missed waiting on the
  131. fwaitingwriterlock and that it's still set (must be done
  132. after acquiring the fwritelock, because otherwise one
  133. writer could reset the fwaitingwriterlock of another one
  134. that's about to wait on it) }
  135. RTLeventResetEvent(fwaitingwriterlock);
  136. { wait until we are the only active thread (no need for memory order
  137. barriers, because RTLeventResetEvent and RTLEventWaitFor imply a
  138. full barrier) }
  139. while System.InterlockedExchangeAdd(factivethreads,0) > 1 do
  140. RTLEventWaitFor(fwaitingwriterlock);
  141. { Make sure that out-of-order execution cannot already perform reads
  142. inside the critical section before the lock has been acquired }
  143. ReadBarrier;
  144. end;
  145. { Count write lock acquisitions by thread }
  146. Inc(p^.RefCount,cNewWriter);
  147. end;
  148. procedure TMultiReadExclusiveWriteSynchronizer.Endwrite;
  149. var
  150. p: PMREWThreadInfo;
  151. begin
  152. p:=PMREWThreadInfo( GetThreadInfo(False) );
  153. { Protect against EndWrite called out of sequence blocking lock }
  154. if (p<>nil) and
  155. ((p^.RefCount and cWriteMask)<>0) then
  156. begin
  157. { Update per thread counter before releasing next write thread }
  158. Dec(p^.RefCount,cNewWriter);
  159. { Finish all writes inside the section, and the update of the RefCount,
  160. so that everything executing afterwards will certainly see these
  161. results }
  162. WriteBarrier;
  163. { Reduce active thread count assuming it was not previously a read lock }
  164. if p^.RefCount=0 then
  165. begin
  166. System.InterlockedDecrement(factivethreads);
  167. { order w.r.t. decrement of fwriterequests below }
  168. WriteBarrier;
  169. end;
  170. { signal potential readers that the coast is clear if all recursive
  171. write locks have been freed }
  172. { Also test for pending write requests }
  173. if System.InterlockedDecrement(fwriterequests)=0 then
  174. begin
  175. { No more writers pending, wake any pending readers }
  176. BasicEventSetEvent(freaderqueue);
  177. end;
  178. { free the writer lock so another writer can become active }
  179. System.LeaveCriticalSection(fwritelock);
  180. { Remove reference to thread if not in use any more }
  181. if p^.RefCount=0 then
  182. RemoveThread(p);
  183. end
  184. else
  185. raise TMREWException.Create('EndWrite called before BeginWrite');
  186. end;
  187. procedure TMultiReadExclusiveWriteSynchronizer.Beginread;
  188. Const
  189. wrSignaled = 0;
  190. wrTimeout = 1;
  191. wrAbandoned= 2;
  192. wrError = 3;
  193. var
  194. p: PMREWThreadInfo;
  195. begin
  196. { Check if we already have a lock, if so grant immediate access }
  197. p:=PMREWThreadInfo( GetThreadInfo(True) );
  198. if p^.RefCount=0 then
  199. begin
  200. { Wanted non-recursive read lock, so increase active threads }
  201. System.InterlockedIncrement(factivethreads);
  202. { wait until there are no more writer active or pending }
  203. ReadWriteBarrier;
  204. while System.InterlockedExchangeAdd(fwriterequests,0)<>0 do
  205. begin
  206. ReadWriteBarrier;
  207. { This thread is not active }
  208. if System.InterlockedDecrement(factivethreads)<>0 then
  209. RTLEventSetEvent(fwaitingwriterlock);
  210. if (BasicEventWaitFor(high(cardinal),freaderqueue) in [wrAbandoned,wrError]) then
  211. raise TMREWException.create('BasicEventWaitFor failed in TMultiReadExclusiveWriteSynchronizer.Beginread');
  212. { Try again to make this thread active }
  213. System.InterlockedIncrement(factivethreads);
  214. { order w.r.t. reading fwriterequests }
  215. ReadWriteBarrier;
  216. end;
  217. { Make sure that out-of-order execution cannot perform reads
  218. inside the critical section before the lock has been acquired }
  219. ReadBarrier;
  220. end;
  221. { Count read lock acquisitions by thread: Inc(p^.RefCount,cNewReader) }
  222. Inc(p^.RefCount);
  223. end;
  224. procedure TMultiReadExclusiveWriteSynchronizer.Endread;
  225. var
  226. p: PMREWThreadInfo;
  227. begin
  228. p:=PMREWThreadInfo( GetThreadInfo(False) );
  229. if (p<>nil) and
  230. ((p^.RefCount and cReadMask)<>0) then
  231. begin
  232. { Update per thread counter: Dec(p^.RefCount,cNewReader) }
  233. Dec(p^.RefCount);
  234. { if this is the last recursive call }
  235. if p^.RefCount=0 then
  236. begin
  237. { Thread no longer has an active lock }
  238. { If no more readers, wake writer in the ready-queue if any.
  239. Every queued thread requesting a write lock increments fwriterequests,
  240. and the first queued writer thread checks factivethreads is active
  241. (will be set already during lock promotion) }
  242. if System.InterlockedDecrement(factivethreads)=1 then
  243. begin
  244. { order w.r.t. access to factivethreads }
  245. ReadBarrier;
  246. if fwriterequests>0 then
  247. RTLEventSetEvent(fwaitingwriterlock);
  248. end;
  249. { remove reference to this thread }
  250. RemoveThread(p);
  251. end;
  252. end
  253. else
  254. raise TMREWException.Create('EndRead called before BeginRead');
  255. end;
  256. function TMultiReadExclusiveWriteSynchronizer.ThreadIDtoIndex(aThreadID: TThreadID): integer;
  257. begin
  258. Result:=
  259. (
  260. ptruint(aThreadID) xor (ptruint(aThreadID) shr 12)
  261. {$ifdef cpu64}
  262. xor (ptruint(aThreadID) shr 32) xor (ptruint(aThreadID) shr 36) xor (ptruint(aThreadID) shr 48)
  263. {$endif}
  264. ) and $FFFF;
  265. Result:=(Result xor (Result shr 4)) and $0F; // Return range 0..15
  266. end;
  267. function TMultiReadExclusiveWriteSynchronizer.GetThreadInfo(AutoCreate: Boolean): Pointer;
  268. var
  269. p: PMREWThreadInfo;
  270. AThreadID: TThreadID;
  271. FreeSlot: Boolean;
  272. OldState: LongInt;
  273. Index: integer;
  274. begin
  275. FreeSlot:=False;
  276. AThreadID:=ThreadID;
  277. Index:=ThreadIDtoIndex( AThreadID );
  278. p:=PMREWThreadInfo(fThreadList[Index]);
  279. while (p<>nil) and
  280. (p^.ThreadID<>AThreadID) do
  281. begin
  282. if p^.Active=cAvail then // Is slot available for use
  283. FreeSlot:=True; // Yes, remember in case we need it as this is a new thread
  284. p:=p^.Next;
  285. ReadBarrier;
  286. end;
  287. if p=nil then
  288. begin
  289. { count threads with locks }
  290. if FreeSlot then
  291. begin
  292. p:=fThreadList[Index];
  293. while (p<>nil) do
  294. begin
  295. if p^.Active=cAvail then
  296. begin
  297. OldState:=InterlockedExchange( p^.Active, cInUse );
  298. if OldState=cAvail then
  299. begin
  300. p^.ThreadID:=AThreadID; // Tag to thread
  301. Break;
  302. end;
  303. end;
  304. p:=p^.Next;
  305. ReadBarrier;
  306. end;
  307. end;
  308. if p=nil then
  309. begin
  310. p:=PMREWThreadInfo(AllocMem(SizeOf(TMREWThreadInfo)));
  311. p^.ThreadID:=AThreadID;
  312. p^.RefCount:=0;
  313. p^.Active:=cInUse;
  314. { Now insert into the chain header }
  315. p^.Next:=p;
  316. WriteBarrier;
  317. { other threads will spin (loop) after the InterlockedExchange
  318. until the field "next" is written, then this node is first in
  319. the forward linked list }
  320. p^.Next:=System.InterlockedExchange(fThreadList[Index],p);
  321. end;
  322. end;
  323. Result:=p;
  324. end;
  325. procedure TMultiReadExclusiveWriteSynchronizer.RemoveThread(AThreadInfo: Pointer);
  326. var
  327. p: PMREWThreadInfo;
  328. begin
  329. p:=PMREWThreadInfo(AThreadInfo);
  330. if p<>nil then
  331. begin
  332. { Prevent matching during GetThreadInfo }
  333. p^.ThreadID:=tthreadid(-1);
  334. WriteBarrier;
  335. { Mark slot available }
  336. p^.Active:=cAvail;
  337. end;
  338. end;
  339. {$endif FPC_HAS_FEATURE_THREADING}