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. if p^.RefCount=0 then
  123. begin
  124. { flush increment of fwriterequests }
  125. WriteBarrier;
  126. System.InterlockedIncrement(factivethreads);
  127. end;
  128. { new readers have to block from now on; writers get priority to avoid
  129. writer starvation (since they have to compete with potentially many
  130. concurrent readers and other writers) }
  131. BasicEventResetEvent(freaderqueue);
  132. { it is possible that earlier on we missed waiting on the
  133. fwaitingwriterlock and that it's still set (must be done
  134. after acquiring the fwritelock, because otherwise one
  135. writer could reset the fwaitingwriterlock of another one
  136. that's about to wait on it) }
  137. RTLeventResetEvent(fwaitingwriterlock);
  138. { wait until we are the only active thread. Get threadinfo
  139. (needs to become a volatile read) }
  140. while factivethreads>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. ReadBarrier;
  205. { must make read volatile }
  206. while fwriterequests<>0 do
  207. begin
  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. ReadBarrier;
  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}