sysuthrd.inc 12 KB

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