History

Renamed folders and separated GSF.Media and GSF.Net into separate projects.

StephenCWills committed 14 years ago

Commit ac1ef661 parent 45bce55628 files · +733 −461Browse files

Showing the changes to Source/Libraries/GSF.Core/Threading (7 of 628 files). Show all

Unified · Split

7 files
  1. Source/Libraries/GSF.Core/Threading/InterprocessLock.cs +522 −0
  2. Source/Libraries/GSF.Core/Threading/InterprocessReaderWriterLock.cs +532 −0
  3. Source/Libraries/GSF.Core/Threading/ManagedThread.cs +715 −0
  4. Source/Libraries/GSF.Core/Threading/ManagedThreadPool.cs +368 −0
  5. Source/Libraries/GSF.Core/Threading/ManagedThreads.cs +442 −0
  6. Source/Libraries/GSF.Core/Threading/NamespaceDoc.cs +244 −0
  7. Source/Libraries/GSF.Core/Threading/ReaderWriterSpinLock.cs +396 −0
Source/Libraries/GSF.Core/Threading/InterprocessLock.cs+522−0
@@ -0,0 +1,522 @@
1//*******************************************************************************************************
2// InterprocessLock.cs - Gbtc
3//
4// Tennessee Valley Authority, 2011
5// No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8// Code in this file licensed to GSF under one or more contributor license agreements listed below.
9//
10// Code Modification History:
11// -----------------------------------------------------------------------------------------------------
12// 03/21/2011 - J. Ritchie Carroll
13// Generated original version of source code.
14// 06/30/2011 - Stephen Wills
15// Applying changes from Jian (Ryan) Zuo: updated to allow unauthorized users to attempt to grant
16// themselves lower than full access to existing mutexes and semaphores.
17// 08/12/2011 - J. Ritchie Carroll
18// Modified creation methods such that locking natives are created in a synchronized fashion.
19// 09/21/2011 - J. Ritchie Carroll
20// Added Mono implementation exception regions.
21//
22//*******************************************************************************************************
23
24#region [ TVA Open Source Agreement ]
25/*
26
27 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
28 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
29 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
30 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
31 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
32 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
33 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
34
35 Original Software Designation: openPDC
36 Original Software Title: The GSF Open Source Phasor Data Concentrator
37 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
38 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
39
40 1. DEFINITIONS
41
42 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
43 that makes a Modification.
44
45 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
46 the use or sale of its Modification alone or when combined with the Subject Software.
47
48 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
49 image, or any other device.
50
51 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
52 another.
53
54 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
55 software separate from the Subject Software that is not governed by the terms of this Agreement.
56
57 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
58 structure of either the Original Software or Subject Software, and includes derivative works, as that
59 term is defined in the Copyright Statute, 17 USC § 101. However, the act of including Subject Software
60 as part of a Larger Work does not in and of itself constitute a Modification.
61
62 G. "Original Software" means the computer software first released under this Agreement by Government
63 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
64
65 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
66 Contributors.
67
68 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
69
70 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
71
72 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
73
74 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
75
76 M. "Use" means the application or employment of the Subject Software for any purpose.
77
78 2. GRANT OF RIGHTS
79
80 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
81 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
82 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
83 the Subject Software:
84
85 1. Use
86
87 2. Distribution
88
89 3. Reproduction
90
91 4. Modification
92
93 5. Redistribution
94
95 6. Display
96
97 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
98 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
99 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
100 pertaining to the Subject Software:
101
102 1. Use
103
104 2. Distribution
105
106 3. Reproduction
107
108 4. Sale
109
110 5. Offer for Sale
111
112 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
113 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
114 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
115 any other combinations that include a Modification.
116
117 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
118 Such sublicense must be under the same terms and conditions of this Agreement.
119
120 3. OBLIGATIONS OF RECIPIENT
121
122 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
123 additions covered under paragraph 3H.
124
125 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
126 must be included with each copy of the Subject Software; and
127
128 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
129 Recipient must also make the source code freely available, and must provide with each copy of the
130 Subject Software information on how to obtain the source code in a reasonable manner on or through a
131 medium customarily used for software exchange.
132
133 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
134 Software:
135
136 No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
137
138 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
139 must identify itself as the originator of its Modification in a manner that reasonably allows
140 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
141 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
142 made and the date of the alterations, identifies Contributor as originator of the alterations, and
143 consents to characterization of the alterations as a Modification, for example, by including a
144 statement that the Modification is derived, directly or indirectly, from Original Software provided by
145 Government Agency. Once consent is granted, it may not thereafter be revoked.
146
147 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
148 been added to the Subject Software, a Recipient may not remove it without the express permission of
149 the Contributor who added the notice.
150
151 E. A Recipient may not make any representation in the Subject Software or in any promotional,
152 advertising or other material that may be construed as an endorsement by Government Agency or by any
153 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
154 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
155
156 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
157 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
158 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
159 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
160 requested that the Recipient inform Government Agency at the web site provided above how to access the
161 Modification.
162
163 G. Each Contributor represents that that its Modification does not violate any existing agreements,
164 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
165 conveyed by this Agreement.
166
167 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
168 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
169 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
170 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
171 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
172 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
173 indemnity and/or liability offered by such Recipient.
174
175 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
176 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
177 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
178 is subject to this Agreement.
179
180 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
181 any goods or technical data from the United States may require some form of export license from the
182 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
183 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
184 required, it shall be issued. Nothing granted herein provides any such export license.
185
186 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
187
188 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
189 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
190 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
191 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
192 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
193 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
194 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
195 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
196 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
197 "AS IS."
198
199 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
200 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
201 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
202 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
203 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
204 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
205 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
206 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
207 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
208 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
209
210 5. GENERAL TERMS
211
212 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
213 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
214 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
215 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
216 Software properly granted by the breaching Recipient shall survive any such termination of this
217 Agreement.
218
219 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
220 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
221
222 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
223 including, but not limited to, determining the validity of this Agreement, the meaning of its
224 provisions and the rights, obligations and remedies of the parties.
225
226 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
227 parties relating to release of the Subject Software and may not be superseded, modified or amended
228 except by further written agreement duly executed by the parties.
229
230 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
231 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
232 Recipient hereby agrees to all terms and conditions herein.
233
234 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
235 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
236
237*/
238#endregion
239
240#region [ Contributor License Agreements ]
241
242//******************************************************************************************************
243//
244// Copyright © 2011, Grid Protection Alliance. All Rights Reserved.
245//
246// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
247// not use this file except in compliance with the License. You may obtain a copy of the License at:
248//
249// http://www.opensource.org/licenses/eclipse-1.0.php
250//
251// Unless agreed to in writing, the subject software distributed under the License is distributed on an
252// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
253// License for the specific language governing permissions and limitations.
254//
255//******************************************************************************************************
256
257#endregion
258
259using GSF.Security.Cryptography;
260using System;
261using System.Runtime.CompilerServices;
262using System.Security.AccessControl;
263using System.Security.Principal;
264using System.Threading;
265
266namespace GSF.Threading
267{
268 /// <summary>
269 /// Defines helper methods related to interprocess locking.
270 /// </summary>
271 public static class InterprocessLock
272 {
273 private const int MutexHash = 0;
274 private const int SemaphoreHash = 1;
275
276 /// <summary>
277 /// Gets a uniquely named interprocess <see cref="Mutex"/> associated with the specified <paramref name="name"/> that identifies a source object
278 /// needing concurrency locking.
279 /// </summary>
280 /// <param name="name">Identifiying name of source object needing concurrency locking (e.g., a path and file name).</param>
281 /// <returns>A uniquely named interprocess <see cref="Mutex"/> specific to <paramref name="name"/>; <see cref="Mutex"/> is created if it does not exist.</returns>
282 /// <remarks>
283 /// <para>
284 /// This function uses a hash of the <paramref name="name"/> when creating the <see cref="Mutex"/>, not the actual <paramref name="name"/> - this way
285 /// restrictions on the <paramref name="name"/> do not need to be a user concern. All processes needing an interprocess <see cref="Mutex"/> need to
286 /// use this same function to ensure access to the same <see cref="Mutex"/>.
287 /// </para>
288 /// <para>
289 /// The <paramref name="name"/> can be a string of any length (must not be empty, null or white space) and is not case-sensitive. All hashes of the
290 /// <paramref name="name"/> used to create the global <see cref="Mutex"/> are first converted to lower case.
291 /// </para>
292 /// <para>
293 /// The <see cref="Mutex"/> created is "Global" meaning that it will be accessible to all active application sessions including terminal service
294 /// sessions. This is accomplished internally by prefixing the <see cref="Mutex"/> name with "Global\"; it is not necessary for the user to be
295 /// concerned with the length or contents of the <paramref name="name"/> in this method as long as the same <paramref name="name"/> is used for
296 /// each application. Do not use this helper function if you need to create a specifically named or non-global <see cref="Mutex"/>, such as when
297 /// you need to interact with another application using a <see cref="Mutex"/> that does not use this function.
298 /// </para>
299 /// </remarks>
300 /// <exception cref="ArgumentNullException">Argument <paramref name="name"/> cannot be empty, null or white space.</exception>
301 [MethodImplAttribute(MethodImplOptions.Synchronized)]
302 public static Mutex GetNamedMutex(string name)
303 {
304 if (string.IsNullOrWhiteSpace(name))
305 throw new ArgumentNullException("name", "Argument cannot be empty, null or white space.");
306
307 Mutex namedMutex = null;
308 bool doesNotExist = false;
309 bool unauthorized = false;
310
311 // Create a mutex name that is specific to an object (e.g., a path and file name).
312 // Prefix mutext name with "Global\" such that mutex will apply to all active
313 // application sessions in case terminal services is running.
314 string mutexName = "Global\\" + Cipher.GetPasswordHash(name.ToLower(), MutexHash).Replace('\\', '-');
315
316 // Attempt to open the named mutex
317 try
318 {
319 namedMutex = Mutex.OpenExisting(mutexName);
320 }
321 catch (WaitHandleCannotBeOpenedException)
322 {
323 doesNotExist = true;
324 }
325 catch (UnauthorizedAccessException)
326 {
327 unauthorized = true;
328 }
329
330 // Mono Mutex implementations do not include ability to change access rules
331#if MONO
332 // If mutex does not exist we create it
333 if (doesNotExist || unauthorized)
334 {
335 try
336 {
337 bool mutexWasCreated;
338
339 namedMutex = new Mutex(false, mutexName, out mutexWasCreated);
340
341 if (!mutexWasCreated)
342 throw new InvalidOperationException("Failed to create mutex.");
343 }
344 catch (UnauthorizedAccessException ex)
345 {
346 throw new InvalidOperationException("Failed to create mutex: " + ex.Message);
347 }
348 }
349#else
350 // If mutex does not exist we create it
351 if (doesNotExist)
352 {
353 try
354 {
355 MutexSecurity security = new MutexSecurity();
356 bool mutexWasCreated;
357
358 security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
359 namedMutex = new Mutex(false, mutexName, out mutexWasCreated, security);
360
361 if (!mutexWasCreated)
362 throw new InvalidOperationException("Failed to create mutex.");
363 }
364 catch (UnauthorizedAccessException)
365 {
366 MutexSecurity security = new MutexSecurity();
367 bool mutexWasCreated;
368
369 security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
370 namedMutex = new Mutex(false, mutexName, out mutexWasCreated, security);
371
372 if (!mutexWasCreated)
373 throw new InvalidOperationException("Failed to create mutex.");
374 }
375 }
376
377 if (unauthorized)
378 {
379 namedMutex = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions);
380
381 // Get the current ACL. This requires MutexRights.ReadPermission
382 MutexSecurity security = namedMutex.GetAccessControl();
383 MutexAccessRule rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
384 security.RemoveAccessRule(rule);
385
386 // Now grant specific user rights for less than full access
387 rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow);
388 security.AddAccessRule(rule);
389
390 // Update the ACL. This requires MutexRighs.ChangePermission.
391 namedMutex.SetAccessControl(security);
392 namedMutex = Mutex.OpenExisting(mutexName);
393 }
394#endif
395
396 return namedMutex;
397 }
398
399 /// <summary>
400 /// Gets a uniquely named interprocess <see cref="Semaphore"/> associated with the specified <paramref name="name"/> that identifies a source object
401 /// needing concurrency locking.
402 /// </summary>
403 /// <param name="name">Identifiying name of source object needing concurrency locking (e.g., a path and file name).</param>
404 /// <param name="maximumCount">The maximum number of requests for the semaphore that can be granted concurrently.</param>
405 /// <param name="initialCount">The initial number of requests for the semaphore that can be granted concurrently, or -1 to default to <paramref name="maximumCount"/>.</param>
406 /// <returns>A uniquely named interprocess <see cref="Semaphore"/> specific to <paramref name="name"/>; <see cref="Semaphore"/> is created if it does not exist.</returns>
407 /// <remarks>
408 /// <para>
409 /// This function uses a hash of the <paramref name="name"/> when creating the <see cref="Semaphore"/>, not the actual <paramref name="name"/> - this way
410 /// restrictions on the <paramref name="name"/> do not need to be a user concern. All processes needing an interprocess <see cref="Semaphore"/> need to
411 /// use this same function to ensure access to the same <see cref="Semaphore"/>.
412 /// </para>
413 /// <para>
414 /// The <paramref name="name"/> can be a string of any length (must not be empty, null or white space) and is not case-sensitive. All hashes of the
415 /// <paramref name="name"/> used to create the global <see cref="Semaphore"/> are first converted to lower case.
416 /// </para>
417 /// <para>
418 /// It is not necessary for the user to be concerned with the length or contents of the <paramref name="name"/> in this method as long as the same
419 /// <paramref name="name"/> is used for each application. Do not use this helper function if you need to create a specifically named <see cref="Semaphore"/>,
420 /// such as when you need to interact with another application using a <see cref="Semaphore"/> that does not use this function.
421 /// </para>
422 /// </remarks>
423 /// <exception cref="ArgumentNullException">Argument <paramref name="name"/> cannot be empty, null or white space.</exception>
424 [MethodImplAttribute(MethodImplOptions.Synchronized)]
425 public static Semaphore GetNamedSemaphore(string name, int maximumCount = 10, int initialCount = -1)
426 {
427 if (string.IsNullOrWhiteSpace(name))
428 throw new ArgumentNullException("name", "Argument cannot be empty, null or white space.");
429
430 Semaphore namedSemaphore = null;
431 bool doesNotExist = false;
432 bool unauthorized = false;
433
434 if (initialCount < 0)
435 initialCount = maximumCount;
436
437 // Create a semaphore name that is specific to an object (e.g., a path and file name).
438 string semaphoreName = Cipher.GetPasswordHash(name.ToLower(), SemaphoreHash).Replace('\\', '-');
439
440 // Attempt to open the named semaphore
441 try
442 {
443 namedSemaphore = Semaphore.OpenExisting(semaphoreName);
444 }
445 catch (WaitHandleCannotBeOpenedException)
446 {
447 doesNotExist = true;
448 }
449 catch (UnauthorizedAccessException)
450 {
451 unauthorized = true;
452 }
453
454 // Mono Semaphore implementations do not include ability to change access rules
455#if MONO
456 // If semaphore does not exist we create it
457 if (doesNotExist || unauthorized)
458 {
459 try
460 {
461 bool semaphoreWasCreated;
462
463 namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated);
464
465 if (!semaphoreWasCreated)
466 throw new InvalidOperationException("Failed to create semaphore.");
467 }
468 catch (UnauthorizedAccessException ex)
469 {
470 throw new InvalidOperationException("Failed to create semaphore: " + ex.Message);
471 }
472 }
473#else
474 // If semaphore does not exist we create it
475 if (doesNotExist)
476 {
477 try
478 {
479 SemaphoreSecurity security = new SemaphoreSecurity();
480 bool semaphoreWasCreated;
481
482 security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow));
483 namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security);
484
485 if (!semaphoreWasCreated)
486 throw new InvalidOperationException("Failed to create semaphore.");
487 }
488 catch (UnauthorizedAccessException)
489 {
490 SemaphoreSecurity security = new SemaphoreSecurity();
491 bool semaphoreWasCreated;
492
493 security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow));
494 namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security);
495
496 if (!semaphoreWasCreated)
497 throw new InvalidOperationException("Failed to create semaphore.");
498 }
499 }
500 else if (unauthorized)
501 {
502 namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions);
503
504 // Get the current ACL. This requires MutexRights.ReadPermission
505 SemaphoreSecurity security = new SemaphoreSecurity();
506 SemaphoreAccessRule rule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow);
507 security.RemoveAccessRule(rule);
508
509 // Now grant specific user rights for less than full access
510 rule = new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow);
511 security.AddAccessRule(rule);
512
513 // Update the ACL. This requires MutexRighs.ChangePermission.
514 namedSemaphore.SetAccessControl(security);
515 namedSemaphore = Semaphore.OpenExisting(semaphoreName);
516 }
517#endif
518
519 return namedSemaphore;
520 }
521 }
522}
Source/Libraries/GSF.Core/Threading/InterprocessReaderWriterLock.cs+532−0
@@ -0,0 +1,532 @@
1//*******************************************************************************************************
2// InterprocessReaderWriterLock.cs - Gbtc
3//
4// Tennessee Valley Authority, 2011
5// No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8// Code in this file licensed to GSF under one or more contributor license agreements listed below.
9//
10// Code Modification History:
11// -----------------------------------------------------------------------------------------------------
12// 03/21/2011 - Ritchie
13// Generated original version of source code.
14//
15//*******************************************************************************************************
16
17#region [ TVA Open Source Agreement ]
18/*
19
20 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
21 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
22 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
23 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
24 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
25 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
26 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
27
28 Original Software Designation: openPDC
29 Original Software Title: The GSF Open Source Phasor Data Concentrator
30 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
31 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
32
33 1. DEFINITIONS
34
35 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
36 that makes a Modification.
37
38 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
39 the use or sale of its Modification alone or when combined with the Subject Software.
40
41 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
42 image, or any other device.
43
44 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
45 another.
46
47 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
48 software separate from the Subject Software that is not governed by the terms of this Agreement.
49
50 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
51 structure of either the Original Software or Subject Software, and includes derivative works, as that
52 term is defined in the Copyright Statute, 17 USC § 101. However, the act of including Subject Software
53 as part of a Larger Work does not in and of itself constitute a Modification.
54
55 G. "Original Software" means the computer software first released under this Agreement by Government
56 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
57
58 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
59 Contributors.
60
61 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
62
63 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
64
65 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
66
67 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
68
69 M. "Use" means the application or employment of the Subject Software for any purpose.
70
71 2. GRANT OF RIGHTS
72
73 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
74 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
75 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
76 the Subject Software:
77
78 1. Use
79
80 2. Distribution
81
82 3. Reproduction
83
84 4. Modification
85
86 5. Redistribution
87
88 6. Display
89
90 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
91 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
92 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
93 pertaining to the Subject Software:
94
95 1. Use
96
97 2. Distribution
98
99 3. Reproduction
100
101 4. Sale
102
103 5. Offer for Sale
104
105 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
106 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
107 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
108 any other combinations that include a Modification.
109
110 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
111 Such sublicense must be under the same terms and conditions of this Agreement.
112
113 3. OBLIGATIONS OF RECIPIENT
114
115 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
116 additions covered under paragraph 3H.
117
118 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
119 must be included with each copy of the Subject Software; and
120
121 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
122 Recipient must also make the source code freely available, and must provide with each copy of the
123 Subject Software information on how to obtain the source code in a reasonable manner on or through a
124 medium customarily used for software exchange.
125
126 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
127 Software:
128
129 No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
130
131 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
132 must identify itself as the originator of its Modification in a manner that reasonably allows
133 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
134 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
135 made and the date of the alterations, identifies Contributor as originator of the alterations, and
136 consents to characterization of the alterations as a Modification, for example, by including a
137 statement that the Modification is derived, directly or indirectly, from Original Software provided by
138 Government Agency. Once consent is granted, it may not thereafter be revoked.
139
140 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
141 been added to the Subject Software, a Recipient may not remove it without the express permission of
142 the Contributor who added the notice.
143
144 E. A Recipient may not make any representation in the Subject Software or in any promotional,
145 advertising or other material that may be construed as an endorsement by Government Agency or by any
146 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
147 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
148
149 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
150 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
151 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
152 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
153 requested that the Recipient inform Government Agency at the web site provided above how to access the
154 Modification.
155
156 G. Each Contributor represents that that its Modification does not violate any existing agreements,
157 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
158 conveyed by this Agreement.
159
160 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
161 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
162 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
163 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
164 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
165 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
166 indemnity and/or liability offered by such Recipient.
167
168 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
169 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
170 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
171 is subject to this Agreement.
172
173 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
174 any goods or technical data from the United States may require some form of export license from the
175 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
176 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
177 required, it shall be issued. Nothing granted herein provides any such export license.
178
179 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
180
181 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
182 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
183 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
184 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
185 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
186 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
187 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
188 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
189 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
190 "AS IS."
191
192 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
193 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
194 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
195 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
196 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
197 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
198 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
199 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
200 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
201 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
202
203 5. GENERAL TERMS
204
205 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
206 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
207 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
208 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
209 Software properly granted by the breaching Recipient shall survive any such termination of this
210 Agreement.
211
212 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
213 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
214
215 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
216 including, but not limited to, determining the validity of this Agreement, the meaning of its
217 provisions and the rights, obligations and remedies of the parties.
218
219 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
220 parties relating to release of the Subject Software and may not be superseded, modified or amended
221 except by further written agreement duly executed by the parties.
222
223 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
224 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
225 Recipient hereby agrees to all terms and conditions herein.
226
227 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
228 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
229
230*/
231#endregion
232
233#region [ Contributor License Agreements ]
234
235//******************************************************************************************************
236//
237// Copyright © 2011, Grid Protection Alliance. All Rights Reserved.
238//
239// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
240// not use this file except in compliance with the License. You may obtain a copy of the License at:
241//
242// http://www.opensource.org/licenses/eclipse-1.0.php
243//
244// Unless agreed to in writing, the subject software distributed under the License is distributed on an
245// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
246// License for the specific language governing permissions and limitations.
247//
248//******************************************************************************************************
249
250#endregion
251
252using System;
253using System.Threading;
254
255namespace GSF.Threading
256{
257 /// <summary>
258 /// Represents an interprocess reader/writer lock using <see cref="Semaphore"/> and <see cref="Mutex"/> native locking mechanisms.
259 /// </summary>
260 public class InterprocessReaderWriterLock : IDisposable
261 {
262 #region [ Members ]
263
264 // Constants
265
266 /// <summary>
267 /// Default maximum concurrent locks allowed for <see cref="InterprocessReaderWriterLock"/>.
268 /// </summary>
269 public const int DefaultMaximumConcurrentLocks = 10;
270
271 // Fields
272 private Mutex m_semaphoreLock; // Mutex used to synchronize access to Semaphore
273 private Semaphore m_concurrencyLock; // Semaphore used for reader/writer lock on consumer object
274 private int m_maximumConcurrentLocks;
275 private bool m_disposed;
276
277 #endregion
278
279 #region [ Constructors ]
280
281 /// <summary>
282 /// Creates a new instance of the <see cref="InterprocessReaderWriterLock"/> associated with the specified
283 /// <paramref name="name"/> that identifies a source object needing concurrency locking.
284 /// </summary>
285 /// <param name="name">Identifiying name of source object needing concurrency locking (e.g., a path and file name).</param>
286 public InterprocessReaderWriterLock(string name)
287 : this(name, DefaultMaximumConcurrentLocks)
288 {
289 }
290
291 /// <summary>
292 /// Creates a new instance of the <see cref="InterprocessReaderWriterLock"/> associated with the specified
293 /// <paramref name="name"/> that identifies a source object needing concurrency locking.
294 /// </summary>
295 /// <param name="name">Identifiying name of source object needing concurrency locking (e.g., a path and file name).</param>
296 /// <param name="maximumConcurrentLocks">Maximum concurrent reader locks to allow.</param>
297 /// <remarks>
298 /// If more reader locks are requested than the <paramref name="maximumConcurrentLocks"/>, excess reader locks will simply
299 /// wait until a lock is available (i.e., one of the existing reads completes).
300 /// </remarks>
301 public InterprocessReaderWriterLock(string name, int maximumConcurrentLocks)
302 {
303 m_maximumConcurrentLocks = maximumConcurrentLocks;
304 m_semaphoreLock = InterprocessLock.GetNamedMutex(name);
305 m_concurrencyLock = InterprocessLock.GetNamedSemaphore(name, m_maximumConcurrentLocks);
306 }
307
308 /// <summary>
309 /// Releases the unmanaged resources before the <see cref="InterprocessReaderWriterLock"/> object is reclaimed by <see cref="GC"/>.
310 /// </summary>
311 ~InterprocessReaderWriterLock()
312 {
313 Dispose(false);
314 }
315
316 #endregion
317
318 #region [ Properties ]
319
320 /// <summary>
321 /// Gets the maximum concurrent reader locks allowed.
322 /// </summary>
323 public int MaximumConcurrentLocks
324 {
325 get
326 {
327 return m_maximumConcurrentLocks;
328 }
329 }
330
331 #endregion
332
333 #region [ Methods ]
334
335 /// <summary>
336 /// Releases all the resources used by the <see cref="InterprocessReaderWriterLock"/> object.
337 /// </summary>
338 public void Dispose()
339 {
340 Dispose(true);
341 GC.SuppressFinalize(this);
342 }
343
344 /// <summary>
345 /// Releases the unmanaged resources used by the <see cref="InterprocessReaderWriterLock"/> object and optionally releases the managed resources.
346 /// </summary>
347 /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
348 protected virtual void Dispose(bool disposing)
349 {
350 if (!m_disposed)
351 {
352 try
353 {
354 if (disposing)
355 {
356 if ((object)m_concurrencyLock != null)
357 m_concurrencyLock.Close();
358 m_concurrencyLock = null;
359
360 if ((object)m_semaphoreLock != null)
361 m_semaphoreLock.Close();
362 m_semaphoreLock = null;
363 }
364 }
365 finally
366 {
367 m_disposed = true; // Prevent duplicate dispose.
368 }
369 }
370 }
371
372 /// <summary>
373 /// Tries to enter the lock in read mode.
374 /// </summary>
375 /// <remarks>
376 /// Upon successful aquistion of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>.
377 /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>.
378 /// </remarks>
379 public void EnterReadLock()
380 {
381 TryEnterReadLock(Timeout.Infinite);
382 }
383
384 /// <summary>
385 /// Tries to enter the lock in write mode.
386 /// </summary>
387 /// <remarks>
388 /// Upon successful aquistion of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>.
389 /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>.
390 /// </remarks>
391 public void EnterWriteLock()
392 {
393 TryEnterWriteLock(Timeout.Infinite);
394 }
395
396 /// <summary>
397 /// Exits read mode and returns the prior read lock count.
398 /// </summary>
399 /// <remarks>
400 /// Upon successful aquistion of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>.
401 /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>.
402 /// </remarks>
403 public int ExitReadLock()
404 {
405 // Release the semaphore lock and restore the slot
406 return m_concurrencyLock.Release();
407 }
408
409 /// <summary>
410 /// Exits write mode.
411 /// </summary>
412 /// <remarks>
413 /// Upon successful aquistion of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>.
414 /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>.
415 /// </remarks>
416 public void ExitWriteLock()
417 {
418 // Release semaphore synchronization mutex lock
419 m_semaphoreLock.ReleaseMutex();
420 }
421
422 /// <summary>
423 /// Tries to enter the lock in read mode, with an optional time-out.
424 /// </summary>
425 /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
426 /// <returns><c>true</c> if the calling thread entered read mode, otherwise, <c>false</c>.</returns>
427 /// <remarks>
428 /// Upon successful aquistion of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>.
429 /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>.
430 /// </remarks>
431 public bool TryEnterReadLock(int millisecondsTimeout)
432 {
433 bool success = false;
434
435 try
436 {
437 // Wait for system level mutex lock to synchronize access to semaphore
438 m_semaphoreLock.WaitOne();
439 }
440 catch (AbandonedMutexException)
441 {
442 // Abnormal application terminations can leave a mutex abandoned, in
443 // this case we now own the mutex so we just ignore the exception
444 }
445
446 try
447 {
448 // Wait for a semaphore slot to become available
449 success = m_concurrencyLock.WaitOne(millisecondsTimeout);
450 }
451 finally
452 {
453 // Release mutex so others can access the semaphore
454 m_semaphoreLock.ReleaseMutex();
455 }
456
457 return success;
458 }
459
460 /// <summary>
461 /// Tries to enter the lock in write mode, with an optional time-out.
462 /// </summary>
463 /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param>
464 /// <returns><c>true</c> if the calling thread entered write mode, otherwise, <c>false</c>.</returns>
465 /// <remarks>
466 /// Upon successful aquistion of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>.
467 /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>.
468 /// </remarks>
469 public bool TryEnterWriteLock(int millisecondsTimeout)
470 {
471 bool success = false;
472 long startTime;
473
474 try
475 {
476 // Wait for system level mutex lock to synchronize access to semaphore
477 m_semaphoreLock.WaitOne();
478 }
479 catch (AbandonedMutexException)
480 {
481 // Abnormal application terminations can leave a mutex abandoned, in
482 // this case we now own the mutex so we just ignore the exception
483 }
484
485 try
486 {
487 // At this point no other threads can aquire read or write access since we own the mutex.
488 // Other threads may be busy reading, so we wait until all semaphore slots become available.
489 // The only way to get a semaphore slot count is to execute a successful wait and release.
490 startTime = DateTime.UtcNow.Ticks;
491
492 if (success = m_concurrencyLock.WaitOne(millisecondsTimeout))
493 {
494 int count = m_concurrencyLock.Release();
495 int adjustedTimeout = millisecondsTimeout;
496
497 // After a successful wait and release the returned semaphore slot count will be -1 of the
498 // actual count since we owned one slot after a successful wait.
499 while (success && count != m_maximumConcurrentLocks - 1)
500 {
501 // Sleep to allow any remaining reads to complete
502 Thread.Sleep(1);
503
504 // Continue to adjust remaining time to accomodate user specified millisecond timeout
505 if (millisecondsTimeout > 0)
506 adjustedTimeout = millisecondsTimeout - (int)Ticks.ToMilliseconds(DateTime.UtcNow.Ticks - startTime);
507
508 if (adjustedTimeout < 0)
509 adjustedTimeout = 0;
510
511 if (success = m_concurrencyLock.WaitOne(adjustedTimeout))
512 count = m_concurrencyLock.Release();
513 }
514 }
515 }
516 finally
517 {
518 // If lock failed, release mutex so others can access the semaphore
519 if (!success)
520 m_semaphoreLock.ReleaseMutex();
521 }
522
523 // Successfully entering write lock leaves state of semphore locking mutex "owned", it is critical that
524 // consumer call ExitWriteLock upon completion of write action to release mutex regardless of whether
525 // their code succeeds or fails, that is, consumer should use the finally clause of a "try/finally"
526 // expression to ExitWriteLock.
527 return success;
528 }
529
530 #endregion
531 }
532}
Source/Libraries/GSF.Core/Threading/ManagedThread.cs+715−0
@@ -0,0 +1,715 @@
1//*******************************************************************************************************
2// ManagedThread.cs - Gbtc
3//
4// Tennessee Valley Authority, 2009
5// No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8// Code in this file licensed to GSF under one or more contributor license agreements listed below.
9//
10// Code Modification History:
11// -----------------------------------------------------------------------------------------------------
12// 01/25/2008 - J. Ritchie Carroll
13// Initial version of source generated.
14// 09/11/2008 - J. Ritchie Carroll
15// Converted to C#.
16// 08/10/2009 - Josh L. Patterson
17// Edited Comments.
18// 09/14/2009 - Stephen C. Wills
19// Added new header and license agreement.
20// 09/22/2011 - J. Ritchie Carroll
21// Added Mono implementation exception regions.
22//
23//*******************************************************************************************************
24
25#region [ TVA Open Source Agreement ]
26/*
27
28 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
29 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
30 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
31 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
32 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
33 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
34 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
35
36 Original Software Designation: openPDC
37 Original Software Title: The GSF Open Source Phasor Data Concentrator
38 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
39 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
40
41 1. DEFINITIONS
42
43 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
44 that makes a Modification.
45
46 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
47 the use or sale of its Modification alone or when combined with the Subject Software.
48
49 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
50 image, or any other device.
51
52 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
53 another.
54
55 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
56 software separate from the Subject Software that is not governed by the terms of this Agreement.
57
58 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
59 structure of either the Original Software or Subject Software, and includes derivative works, as that
60 term is defined in the Copyright Statute, 17 USC � 101. However, the act of including Subject Software
61 as part of a Larger Work does not in and of itself constitute a Modification.
62
63 G. "Original Software" means the computer software first released under this Agreement by Government
64 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
65
66 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
67 Contributors.
68
69 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
70
71 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
72
73 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
74
75 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
76
77 M. "Use" means the application or employment of the Subject Software for any purpose.
78
79 2. GRANT OF RIGHTS
80
81 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
82 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
83 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
84 the Subject Software:
85
86 1. Use
87
88 2. Distribution
89
90 3. Reproduction
91
92 4. Modification
93
94 5. Redistribution
95
96 6. Display
97
98 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
99 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
100 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
101 pertaining to the Subject Software:
102
103 1. Use
104
105 2. Distribution
106
107 3. Reproduction
108
109 4. Sale
110
111 5. Offer for Sale
112
113 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
114 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
115 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
116 any other combinations that include a Modification.
117
118 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
119 Such sublicense must be under the same terms and conditions of this Agreement.
120
121 3. OBLIGATIONS OF RECIPIENT
122
123 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
124 additions covered under paragraph 3H.
125
126 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
127 must be included with each copy of the Subject Software; and
128
129 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
130 Recipient must also make the source code freely available, and must provide with each copy of the
131 Subject Software information on how to obtain the source code in a reasonable manner on or through a
132 medium customarily used for software exchange.
133
134 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
135 Software:
136
137 No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
138
139 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
140 must identify itself as the originator of its Modification in a manner that reasonably allows
141 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
142 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
143 made and the date of the alterations, identifies Contributor as originator of the alterations, and
144 consents to characterization of the alterations as a Modification, for example, by including a
145 statement that the Modification is derived, directly or indirectly, from Original Software provided by
146 Government Agency. Once consent is granted, it may not thereafter be revoked.
147
148 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
149 been added to the Subject Software, a Recipient may not remove it without the express permission of
150 the Contributor who added the notice.
151
152 E. A Recipient may not make any representation in the Subject Software or in any promotional,
153 advertising or other material that may be construed as an endorsement by Government Agency or by any
154 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
155 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
156
157 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
158 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
159 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
160 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
161 requested that the Recipient inform Government Agency at the web site provided above how to access the
162 Modification.
163
164 G. Each Contributor represents that that its Modification does not violate any existing agreements,
165 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
166 conveyed by this Agreement.
167
168 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
169 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
170 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
171 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
172 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
173 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
174 indemnity and/or liability offered by such Recipient.
175
176 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
177 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
178 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
179 is subject to this Agreement.
180
181 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
182 any goods or technical data from the United States may require some form of export license from the
183 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
184 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
185 required, it shall be issued. Nothing granted herein provides any such export license.
186
187 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
188
189 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
190 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
191 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
192 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
193 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
194 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
195 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
196 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
197 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
198 "AS IS."
199
200 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
201 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
202 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
203 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
204 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
205 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
206 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
207 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
208 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
209 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
210
211 5. GENERAL TERMS
212
213 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
214 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
215 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
216 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
217 Software properly granted by the breaching Recipient shall survive any such termination of this
218 Agreement.
219
220 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
221 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
222
223 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
224 including, but not limited to, determining the validity of this Agreement, the meaning of its
225 provisions and the rights, obligations and remedies of the parties.
226
227 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
228 parties relating to release of the Subject Software and may not be superseded, modified or amended
229 except by further written agreement duly executed by the parties.
230
231 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
232 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
233 Recipient hereby agrees to all terms and conditions herein.
234
235 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
236 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
237
238*/
239#endregion
240
241#region [ Contributor License Agreements ]
242
243//******************************************************************************************************
244//
245// Copyright � 2011, Grid Protection Alliance. All Rights Reserved.
246//
247// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
248// not use this file except in compliance with the License. You may obtain a copy of the License at:
249//
250// http://www.opensource.org/licenses/eclipse-1.0.php
251//
252// Unless agreed to in writing, the subject software distributed under the License is distributed on an
253// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
254// License for the specific language governing permissions and limitations.
255//
256//******************************************************************************************************
257
258#endregion
259
260using GSF.Units;
261using System;
262using System.Threading;
263
264namespace GSF.Threading
265{
266 #region [ Enumerations ]
267
268 /// <summary>
269 /// Managed Thread Types
270 /// </summary>
271 public enum ThreadType
272 {
273 /// <summary>Standard thread created with public constructor</summary>
274 StandardThread,
275 /// <summary>Queued thread added into managed thread pool</summary>
276 QueuedThread
277 }
278
279 /// <summary>
280 /// Managed Thread States
281 /// </summary>
282 public enum ThreadStatus
283 {
284 /// <summary>Thread created, not started</summary>
285 Unstarted,
286 /// <summary>Thread queued for execution</summary>
287 Queued,
288 /// <summary>Thread start requested, execution pending</summary>
289 Started,
290 /// <summary>Thread executing</summary>
291 Executing,
292 /// <summary>Thread completed</summary>
293 Completed,
294 /// <summary>Thread aborted</summary>
295 Aborted
296 }
297
298 #endregion
299
300 /// <summary>
301 /// Defines a managed thread
302 /// </summary>
303 /// <remarks>
304 /// This class works like any normal thread but provides the benefit of automatic tracking
305 /// through the ManagedThreads collection, total thread runtime and the ability to run
306 /// the thread in an alternate execution context
307 /// </remarks>
308 public sealed class ManagedThread
309 {
310 #region [ Members ]
311
312 // Fields
313 private Thread m_thread;
314 private ThreadType m_type;
315 private ThreadStatus m_status;
316 private string m_name;
317 private Ticks m_startTime;
318 private Ticks m_stopTime;
319 private ContextCallback m_ctxCallback;
320 private ThreadStart m_tsCallback;
321 private ParameterizedThreadStart m_ptsCallback;
322 private ExecutionContext m_ctx;
323 private object m_state;
324 private object m_tag;
325
326 #endregion
327
328 #region [ Constructors ]
329
330 /// <summary>
331 /// Initializes a new instance of the ManagedThread class.
332 /// </summary>
333 /// <param name="callback">A <see cref="ThreadStart"/> object.</param>
334 public ManagedThread(ThreadStart callback)
335 : this(ThreadType.StandardThread, callback, null, null)
336 {
337 m_thread = new Thread(HandleItem);
338 }
339
340 /// <summary>
341 /// Initializes a new instance of the ManagedThread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.
342 /// </summary>
343 /// <param name="callback">A <see cref="ParameterizedThreadStart"/> object.</param>
344 public ManagedThread(ParameterizedThreadStart callback)
345 : this(ThreadType.StandardThread, callback, null, null)
346 {
347 m_thread = new Thread(HandleItem);
348 }
349
350#if !MONO
351 /// <summary>
352 /// Initializes a new instance of the ManagedThread class, specifying a delegate that allows an object to be passed to the thread when the thread is started
353 /// and allowing the user to specify an alternate execution context for the thread.
354 /// </summary>
355 /// <param name="callback">A <see cref="ContextCallback"/> delgate to execute.</param>
356 /// <param name="ctx">An <see cref="ExecutionContext"/>.</param>
357 public ManagedThread(ContextCallback callback, ExecutionContext ctx)
358 : this(ThreadType.StandardThread, callback, null, ctx)
359 {
360 m_thread = new Thread(HandleItem);
361 }
362#endif
363
364 internal ManagedThread(ThreadType type, ThreadStart callback, object state, ExecutionContext ctx)
365 {
366 m_type = type;
367 m_status = (type == ThreadType.QueuedThread ? ThreadStatus.Queued : ThreadStatus.Unstarted);
368 m_tsCallback = callback;
369 m_state = state;
370 m_ctx = ctx;
371 }
372
373 internal ManagedThread(ThreadType type, ParameterizedThreadStart callback, object state, ExecutionContext ctx)
374 {
375 m_type = type;
376 m_status = (type == ThreadType.QueuedThread ? ThreadStatus.Queued : ThreadStatus.Unstarted);
377 m_ptsCallback = callback;
378 m_state = state;
379 m_ctx = ctx;
380 }
381
382 internal ManagedThread(ThreadType type, ContextCallback callback, object state, ExecutionContext ctx)
383 {
384 m_type = type;
385 m_status = (type == ThreadType.QueuedThread ? ThreadStatus.Queued : ThreadStatus.Unstarted);
386 m_ctxCallback = callback;
387 m_state = state;
388 m_ctx = ctx;
389 }
390
391 #endregion
392
393 #region [ Properties ]
394
395 /// <summary>
396 /// An object containing data to be used by the thread's execution method.
397 /// </summary>
398 public object State
399 {
400 get
401 {
402 return m_state;
403 }
404 set
405 {
406 m_state = value;
407 }
408 }
409
410 /// <summary>
411 /// An object that allows additional user defined information to be tracked along with this thread.
412 /// </summary>
413 public object Tag
414 {
415 get
416 {
417 return m_tag;
418 }
419 set
420 {
421 m_tag = value;
422 }
423 }
424
425 /// <summary>
426 /// Returns the managed thread type (either StandardThread or QueuedThread)
427 /// </summary>
428 public ThreadType Type
429 {
430 get
431 {
432 return m_type;
433 }
434 }
435
436 /// <summary>
437 /// Gets a value containing the curretn status of the current thread.
438 /// </summary>
439 public ThreadStatus Status
440 {
441 get
442 {
443 return m_status;
444 }
445 internal set
446 {
447 m_status = value;
448 }
449 }
450
451 /// <summary>
452 /// Gets a value indicating the execution status of the current thread.
453 /// </summary>
454 public bool IsAlive
455 {
456 get
457 {
458 return (m_status == ThreadStatus.Started || m_status == ThreadStatus.Executing);
459 }
460 }
461
462 /// <summary>
463 /// Gets or sets the name of the thread.
464 /// </summary>
465 public string Name
466 {
467 get
468 {
469 return m_name;
470 }
471 set
472 {
473 m_name = value;
474
475 if (m_type == ThreadType.StandardThread)
476 m_thread.Name = value;
477 }
478 }
479
480 /// <summary>
481 /// Get the time, in ticks, that the thread started executing
482 /// </summary>
483 public Ticks StartTime
484 {
485 get
486 {
487 return m_startTime;
488 }
489 }
490
491 /// <summary>
492 /// Get the time, in ticks, that the thread finished executing
493 /// </summary>
494 public Ticks StopTime
495 {
496 get
497 {
498 return m_stopTime;
499 }
500 }
501
502 /// <summary>
503 /// Gets the total amount of time, in seconds, that the managed thread has been active.
504 /// </summary>
505 public Time RunTime
506 {
507 get
508 {
509 Ticks processingTime = 0;
510
511 if (m_startTime > 0)
512 {
513 if (m_stopTime > 0)
514 processingTime = m_stopTime - m_startTime;
515 else
516 processingTime = DateTime.UtcNow.Ticks - m_startTime;
517 }
518
519 if (processingTime < 0)
520 processingTime = 0;
521
522 return processingTime.ToSeconds();
523 }
524 }
525
526 /// <summary>
527 /// Gets or sets a value indicating the scheduling priority of a thread.
528 /// </summary>
529 /// <returns>One of the ThreadPriority values. The default value is Normal.</returns>
530 /// <remarks>
531 /// Changing of this value is only available to standard threads - you can't change the priorty of queued threads since they are already
532 /// allocated and owned by the .NET thread pool.
533 /// </remarks>
534 public ThreadPriority Priority
535 {
536 get
537 {
538 if (m_type == ThreadType.QueuedThread)
539 {
540 return ThreadPriority.Normal;
541 }
542 else
543 {
544 return m_thread.Priority;
545 }
546 }
547 set
548 {
549 if (m_type == ThreadType.QueuedThread)
550 throw new InvalidOperationException("Cannot change priority of a thread that was queued into thread pool");
551
552 m_thread.Priority = value;
553 }
554 }
555
556 internal Thread Thread
557 {
558 get
559 {
560 return m_thread;
561 }
562 set
563 {
564 m_thread = value;
565 }
566 }
567
568 #endregion
569
570 #region [ Methods ]
571
572 /// <summary>
573 /// Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
574 /// </summary>
575 public void Abort()
576 {
577 ManagedThreads.Cancel(this, true, null);
578 }
579
580 /// <summary>
581 /// Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
582 /// </summary>
583 /// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted.</param>
584 public void Abort(object stateInfo)
585 {
586 ManagedThreads.Cancel(this, true, stateInfo);
587 }
588
589 /// <summary>
590 /// Causes a thread to be scheduled for execution.
591 /// </summary>
592 public void Start()
593 {
594 if (m_type == ThreadType.QueuedThread)
595 throw new InvalidOperationException("Cannot manually start a thread that was queued into thread pool");
596
597 ManagedThreads.Add(this);
598
599 m_thread.Start();
600 }
601
602 /// <summary>
603 /// Causes a thread to be scheduled for execution.
604 /// </summary>
605 /// <param name="parameter">An object that contains data to be used by the method the thread executes.</param>
606 public void Start(object parameter)
607 {
608 if (m_type == ThreadType.QueuedThread)
609 throw new InvalidOperationException("Cannot manually start a thread that was queued into thread pool");
610
611 m_state = parameter;
612
613 ManagedThreads.Add(this);
614
615 m_thread.Start();
616 }
617
618 /// <summary>
619 /// Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
620 /// </summary>
621 /// <remarks>
622 /// This is only available for standard threads - queued threads don't have an associated thread until they are executing.
623 /// </remarks>
624 public void Join()
625 {
626 if (m_type == ThreadType.QueuedThread)
627 throw new InvalidOperationException("Cannot join a thread that was queued into thread pool");
628
629 if (!IsAlive)
630 throw new InvalidOperationException("Cannot join a thread that has not been started");
631
632 m_thread.Join();
633 }
634
635 /// <summary>
636 /// Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
637 /// </summary>
638 /// <param name="millisecondsTimeout">The number of milliseconds to wait for the thread to terminate. </param>
639 /// <returns>true if the thread has terminated; false if the thread has not terminated after the amount of time specified by the millisecondsTimeout parameter has elapsed.</returns>
640 /// <remarks>
641 /// This is only available for standard threads - queued threads don't have an associated thread until they are executing.
642 /// </remarks>
643 public bool Join(int millisecondsTimeout)
644 {
645 if (m_type == ThreadType.QueuedThread)
646 throw new InvalidOperationException("Cannot join a thread that was queued into thread pool.");
647
648 if (!IsAlive)
649 throw new InvalidOperationException("Cannot join a thread that has not been started.");
650
651 return m_thread.Join(millisecondsTimeout);
652 }
653
654 /// <summary>
655 /// Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
656 /// </summary>
657 /// <param name="timeout">A TimeSpan set to the amount of time to wait for the thread to terminate. </param>
658 /// <returns>true if the thread terminated; false if the thread has not terminated after the amount of time specified by the timeout parameter has elapsed.</returns>
659 /// <remarks>
660 /// This is only available for standard threads - queued threads don't have an associated thread until they are executing.
661 /// </remarks>
662 public bool Join(TimeSpan timeout)
663 {
664 return Join((int)timeout.TotalMilliseconds);
665 }
666
667 internal void HandleItem()
668 {
669 // Set start state
670 m_startTime = DateTime.UtcNow.Ticks;
671 m_status = ThreadStatus.Executing;
672
673 try
674 {
675 // Invoke the user's call back function
676 if ((object)m_ctx == null)
677 {
678 if ((object)m_tsCallback != null)
679 {
680 m_tsCallback.Invoke();
681 }
682 else if ((object)m_ptsCallback != null)
683 {
684 m_ptsCallback.Invoke(m_state);
685 }
686 else
687 {
688 m_ctxCallback.Invoke(m_state);
689 }
690 }
691#if !MONO
692 else
693 {
694 // If user specified an alternate execution context, we invoke
695 // their delegate under that context
696 ExecutionContext.Run(m_ctx, m_ctxCallback, m_state);
697 }
698#endif
699 }
700 finally
701 {
702 // Set finish state
703 if (m_status == ThreadStatus.Executing)
704 {
705 m_status = ThreadStatus.Completed;
706 }
707 m_stopTime = DateTime.UtcNow.Ticks;
708
709 ManagedThreads.Remove(this);
710 }
711 }
712
713 #endregion
714 }
715}
Source/Libraries/GSF.Core/Threading/ManagedThreadPool.cs+368−0
@@ -0,0 +1,368 @@
1//*******************************************************************************************************
2// ManagedThreadPool.cs - Gbtc
3//
4// Tennessee Valley Authority, 2009
5// No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8//
9// Code Modification History:
10// -----------------------------------------------------------------------------------------------------
11// 01/25/2008 - J. Ritchie Carroll
12// Initial version of source generated.
13// 09/11/2008 - J. Ritchie Carroll
14// Converted to C#.
15// 09/14/2009 - Stephen C. Wills
16// Added new header and license agreement.
17//
18//*******************************************************************************************************
19
20#region [ TVA Open Source Agreement ]
21/*
22
23 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
24 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
25 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
26 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
27 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
28 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
29 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
30
31 Original Software Designation: openPDC
32 Original Software Title: The GSF Open Source Phasor Data Concentrator
33 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
34 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
35
36 1. DEFINITIONS
37
38 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
39 that makes a Modification.
40
41 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
42 the use or sale of its Modification alone or when combined with the Subject Software.
43
44 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
45 image, or any other device.
46
47 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
48 another.
49
50 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
51 software separate from the Subject Software that is not governed by the terms of this Agreement.
52
53 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
54 structure of either the Original Software or Subject Software, and includes derivative works, as that
55 term is defined in the Copyright Statute, 17 USC � 101. However, the act of including Subject Software
56 as part of a Larger Work does not in and of itself constitute a Modification.
57
58 G. "Original Software" means the computer software first released under this Agreement by Government
59 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
60
61 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
62 Contributors.
63
64 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
65
66 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
67
68 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
69
70 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
71
72 M. "Use" means the application or employment of the Subject Software for any purpose.
73
74 2. GRANT OF RIGHTS
75
76 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
77 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
78 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
79 the Subject Software:
80
81 1. Use
82
83 2. Distribution
84
85 3. Reproduction
86
87 4. Modification
88
89 5. Redistribution
90
91 6. Display
92
93 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
94 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
95 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
96 pertaining to the Subject Software:
97
98 1. Use
99
100 2. Distribution
101
102 3. Reproduction
103
104 4. Sale
105
106 5. Offer for Sale
107
108 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
109 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
110 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
111 any other combinations that include a Modification.
112
113 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
114 Such sublicense must be under the same terms and conditions of this Agreement.
115
116 3. OBLIGATIONS OF RECIPIENT
117
118 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
119 additions covered under paragraph 3H.
120
121 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
122 must be included with each copy of the Subject Software; and
123
124 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
125 Recipient must also make the source code freely available, and must provide with each copy of the
126 Subject Software information on how to obtain the source code in a reasonable manner on or through a
127 medium customarily used for software exchange.
128
129 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
130 Software:
131
132 No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
133
134 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
135 must identify itself as the originator of its Modification in a manner that reasonably allows
136 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
137 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
138 made and the date of the alterations, identifies Contributor as originator of the alterations, and
139 consents to characterization of the alterations as a Modification, for example, by including a
140 statement that the Modification is derived, directly or indirectly, from Original Software provided by
141 Government Agency. Once consent is granted, it may not thereafter be revoked.
142
143 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
144 been added to the Subject Software, a Recipient may not remove it without the express permission of
145 the Contributor who added the notice.
146
147 E. A Recipient may not make any representation in the Subject Software or in any promotional,
148 advertising or other material that may be construed as an endorsement by Government Agency or by any
149 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
150 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
151
152 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
153 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
154 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
155 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
156 requested that the Recipient inform Government Agency at the web site provided above how to access the
157 Modification.
158
159 G. Each Contributor represents that that its Modification does not violate any existing agreements,
160 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
161 conveyed by this Agreement.
162
163 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
164 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
165 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
166 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
167 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
168 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
169 indemnity and/or liability offered by such Recipient.
170
171 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
172 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
173 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
174 is subject to this Agreement.
175
176 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
177 any goods or technical data from the United States may require some form of export license from the
178 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
179 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
180 required, it shall be issued. Nothing granted herein provides any such export license.
181
182 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
183
184 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
185 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
186 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
187 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
188 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
189 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
190 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
191 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
192 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
193 "AS IS."
194
195 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
196 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
197 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
198 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
199 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
200 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
201 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
202 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
203 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
204 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
205
206 5. GENERAL TERMS
207
208 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
209 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
210 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
211 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
212 Software properly granted by the breaching Recipient shall survive any such termination of this
213 Agreement.
214
215 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
216 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
217
218 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
219 including, but not limited to, determining the validity of this Agreement, the meaning of its
220 provisions and the rights, obligations and remedies of the parties.
221
222 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
223 parties relating to release of the Subject Software and may not be superseded, modified or amended
224 except by further written agreement duly executed by the parties.
225
226 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
227 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
228 Recipient hereby agrees to all terms and conditions herein.
229
230 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
231 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
232
233*/
234#endregion
235
236using System;
237using System.Threading;
238
239namespace GSF.Threading
240{
241 /// <summary>
242 /// Defines a managed thread pool
243 /// </summary>
244 /// <remarks>
245 /// This class works like the normal thread pool but provides the benefit of automatic tracking
246 /// of queued threads through the ManagedThreads collection, returns a reference to the
247 /// queued thread with the ability to dequeue and/or abort, total thread runtime and the
248 /// ability to run the queued thread in an alternate execution context
249 /// </remarks>
250 public static class ManagedThreadPool
251 {
252 /// <summary>
253 /// Queues a work item for processing on the managed thread pool
254 /// </summary>
255 /// <param name="callback">A WaitCallback representing the method to execute.</param>
256 /// <returns>Reference to queued thread</returns>
257 /// <remarks>
258 /// This differs from the normal thread pool QueueUserWorkItem function in that it does
259 /// not return a success value determing if item was queued, but rather a reference to
260 /// to the managed thread that was actually placed on the queue.
261 /// </remarks>
262 public static ManagedThread QueueUserWorkItem(ThreadStart callback)
263 {
264 if ((object)callback == null)
265 throw (new ArgumentNullException("callback"));
266
267 ManagedThread item = new ManagedThread(ThreadType.QueuedThread, callback, null, null);
268
269 ManagedThreads.Queue(item);
270
271 ThreadPool.QueueUserWorkItem(HandleItem);
272
273 return item;
274 }
275
276 /// <summary>
277 /// Queues a work item for processing on the managed thread pool
278 /// </summary>
279 /// <param name="callback">A WaitCallback representing the method to execute.</param>
280 /// <returns>Reference to queued thread</returns>
281 /// <remarks>
282 /// This differs from the normal thread pool QueueUserWorkItem function in that it does
283 /// not return a success value determing if item was queued, but rather a reference to
284 /// to the managed thread that was actually placed on the queue.
285 /// </remarks>
286 public static ManagedThread QueueUserWorkItem(ParameterizedThreadStart callback)
287 {
288 return QueueUserWorkItem(callback, null);
289 }
290
291 /// <summary>
292 /// Queues a work item for processing on the managed thread pool
293 /// </summary>
294 /// <param name="callback">A WaitCallback representing the method to execute.</param>
295 /// <param name="state">An object containing data to be used by the method.</param>
296 /// <returns>Reference to queued thread</returns>
297 /// <remarks>
298 /// This differs from the normal thread pool QueueUserWorkItem function in that it does
299 /// not return a success value determing if item was queued, but rather a reference to
300 /// to the managed thread that was actually placed on the queue.
301 /// </remarks>
302 public static ManagedThread QueueUserWorkItem(ParameterizedThreadStart callback, object state)
303 {
304 if ((object)callback == null)
305 throw (new ArgumentNullException("callback"));
306
307 ManagedThread item = new ManagedThread(ThreadType.QueuedThread, callback, state, null);
308
309 ManagedThreads.Queue(item);
310
311 ThreadPool.QueueUserWorkItem(HandleItem);
312
313 return item;
314 }
315
316 /// <summary>
317 /// Queues a work item for processing on the managed thread pool
318 /// </summary>
319 /// <param name="callback">A WaitCallback representing the method to execute.</param>
320 /// <param name="ctx">Alternate execution context in which to run the thread.</param>
321 /// <returns>Reference to queued thread</returns>
322 /// <remarks>
323 /// This differs from the normal thread pool QueueUserWorkItem function in that it does
324 /// not return a success value determing if item was queued, but rather a reference to
325 /// to the managed thread that was actually placed on the queue.
326 /// </remarks>
327 public static ManagedThread QueueUserWorkItem(ContextCallback callback, ExecutionContext ctx)
328 {
329 return QueueUserWorkItem(callback, null, ctx);
330 }
331
332 /// <summary>
333 /// Queues a work item for processing on the managed thread pool
334 /// </summary>
335 /// <param name="callback">A WaitCallback representing the method to execute.</param>
336 /// <param name="state">An object containing data to be used by the method.</param>
337 /// <param name="ctx">Alternate execution context in which to run the thread.</param>
338 /// <returns>Reference to queued thread</returns>
339 /// <remarks>
340 /// This differs from the normal thread pool QueueUserWorkItem function in that it does
341 /// not return a success value determing if item was queued, but rather a reference to
342 /// to the managed thread that was actually placed on the queue.
343 /// </remarks>
344 public static ManagedThread QueueUserWorkItem(ContextCallback callback, object state, ExecutionContext ctx)
345 {
346 if ((object)callback == null)
347 throw (new ArgumentNullException("callback"));
348
349 ManagedThread item = new ManagedThread(ThreadType.QueuedThread, callback, state, ctx);
350
351 ManagedThreads.Queue(item);
352
353 ThreadPool.QueueUserWorkItem(HandleItem);
354
355 return item;
356 }
357
358 private static void HandleItem(object state)
359 {
360 // Get next queued item
361 ManagedThread item = ManagedThreads.Pop();
362
363 // Execute callback...
364 if ((object)item != null)
365 item.HandleItem();
366 }
367 }
368}
Source/Libraries/GSF.Core/Threading/ManagedThreads.cs+442−0
@@ -0,0 +1,442 @@
1//*******************************************************************************************************
2// ManagedThreads.cs - Gbtc
3//
4// Tennessee Valley Authority, 2009
5// No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8//
9// Code Modification History:
10// -----------------------------------------------------------------------------------------------------
11// 01/25/2008 - J. Ritchie Carroll
12// Initial version of source generated.
13// 09/11/2008 - J. Ritchie Carroll
14// Converted to C#.
15// 09/14/2009 - Stephen C. Wills
16// Added new header and license agreement.
17//
18//*******************************************************************************************************
19
20#region [ TVA Open Source Agreement ]
21/*
22
23 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
24 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
25 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
26 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
27 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
28 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
29 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
30
31 Original Software Designation: openPDC
32 Original Software Title: The GSF Open Source Phasor Data Concentrator
33 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
34 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
35
36 1. DEFINITIONS
37
38 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
39 that makes a Modification.
40
41 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
42 the use or sale of its Modification alone or when combined with the Subject Software.
43
44 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
45 image, or any other device.
46
47 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
48 another.
49
50 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
51 software separate from the Subject Software that is not governed by the terms of this Agreement.
52
53 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
54 structure of either the Original Software or Subject Software, and includes derivative works, as that
55 term is defined in the Copyright Statute, 17 USC � 101. However, the act of including Subject Software
56 as part of a Larger Work does not in and of itself constitute a Modification.
57
58 G. "Original Software" means the computer software first released under this Agreement by Government
59 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
60
61 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
62 Contributors.
63
64 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
65
66 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
67
68 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
69
70 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
71
72 M. "Use" means the application or employment of the Subject Software for any purpose.
73
74 2. GRANT OF RIGHTS
75
76 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
77 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
78 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
79 the Subject Software:
80
81 1. Use
82
83 2. Distribution
84
85 3. Reproduction
86
87 4. Modification
88
89 5. Redistribution
90
91 6. Display
92
93 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
94 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
95 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
96 pertaining to the Subject Software:
97
98 1. Use
99
100 2. Distribution
101
102 3. Reproduction
103
104 4. Sale
105
106 5. Offer for Sale
107
108 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
109 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
110 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
111 any other combinations that include a Modification.
112
113 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
114 Such sublicense must be under the same terms and conditions of this Agreement.
115
116 3. OBLIGATIONS OF RECIPIENT
117
118 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
119 additions covered under paragraph 3H.
120
121 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
122 must be included with each copy of the Subject Software; and
123
124 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
125 Recipient must also make the source code freely available, and must provide with each copy of the
126 Subject Software information on how to obtain the source code in a reasonable manner on or through a
127 medium customarily used for software exchange.
128
129 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
130 Software:
131
132 No copyright is claimed pursuant to 17 USC � 105. All Other Rights Reserved.
133
134 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
135 must identify itself as the originator of its Modification in a manner that reasonably allows
136 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
137 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
138 made and the date of the alterations, identifies Contributor as originator of the alterations, and
139 consents to characterization of the alterations as a Modification, for example, by including a
140 statement that the Modification is derived, directly or indirectly, from Original Software provided by
141 Government Agency. Once consent is granted, it may not thereafter be revoked.
142
143 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
144 been added to the Subject Software, a Recipient may not remove it without the express permission of
145 the Contributor who added the notice.
146
147 E. A Recipient may not make any representation in the Subject Software or in any promotional,
148 advertising or other material that may be construed as an endorsement by Government Agency or by any
149 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
150 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
151
152 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
153 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
154 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
155 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
156 requested that the Recipient inform Government Agency at the web site provided above how to access the
157 Modification.
158
159 G. Each Contributor represents that that its Modification does not violate any existing agreements,
160 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
161 conveyed by this Agreement.
162
163 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
164 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
165 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
166 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
167 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
168 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
169 indemnity and/or liability offered by such Recipient.
170
171 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
172 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
173 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
174 is subject to this Agreement.
175
176 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
177 any goods or technical data from the United States may require some form of export license from the
178 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
179 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
180 required, it shall be issued. Nothing granted herein provides any such export license.
181
182 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
183
184 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
185 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
186 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
187 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
188 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
189 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
190 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
191 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
192 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
193 "AS IS."
194
195 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
196 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
197 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
198 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
199 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
200 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
201 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
202 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
203 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
204 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
205
206 5. GENERAL TERMS
207
208 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
209 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
210 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
211 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
212 Software properly granted by the breaching Recipient shall survive any such termination of this
213 Agreement.
214
215 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
216 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
217
218 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
219 including, but not limited to, determining the validity of this Agreement, the meaning of its
220 provisions and the rights, obligations and remedies of the parties.
221
222 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
223 parties relating to release of the Subject Software and may not be superseded, modified or amended
224 except by further written agreement duly executed by the parties.
225
226 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
227 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
228 Recipient hereby agrees to all terms and conditions herein.
229
230 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
231 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
232
233*/
234#endregion
235
236using System;
237using System.Collections.Generic;
238using System.Text;
239using System.Threading;
240
241namespace GSF.Threading
242{
243 /// <summary>
244 /// Maintains a reference to all managed threads
245 /// </summary>
246 public static class ManagedThreads
247 {
248 private static LinkedList<ManagedThread> s_queuedThreads;
249 private static LinkedList<ManagedThread> s_activeThreads;
250
251 static ManagedThreads()
252 {
253 s_queuedThreads = new LinkedList<ManagedThread>();
254 s_activeThreads = new LinkedList<ManagedThread>();
255 }
256
257 /// <summary>
258 /// Add an item to the active thread list
259 /// </summary>
260 /// <remarks>
261 /// Typically only used by standard threads when user calls "Start"
262 /// </remarks>
263 internal static void Add(ManagedThread item)
264 {
265 // Standard threads are simply added to the active thread list when started
266 lock (s_queuedThreads)
267 {
268 item.Status = ThreadStatus.Started;
269 s_activeThreads.AddLast(item);
270 }
271 }
272
273 /// <summary>
274 /// Remove completed thread from active thread list
275 /// </summary>
276 internal static void Remove(ManagedThread item)
277 {
278 lock (s_queuedThreads)
279 {
280 s_activeThreads.Remove(item);
281 }
282 }
283
284 /// <summary>
285 /// Queue thread for processing
286 /// </summary>
287 /// <remarks>
288 /// Typically only used by queued threads to add work items to the queue
289 /// </remarks>
290 internal static void Queue(ManagedThread item)
291 {
292 lock (s_queuedThreads)
293 {
294 s_queuedThreads.AddLast(item);
295 }
296 }
297
298 /// <summary>
299 /// Removes first item from the queue and transfers the item to the active thread list
300 /// </summary>
301 /// <returns>Next item to be processed</returns>
302 internal static ManagedThread Pop()
303 {
304 ManagedThread item = null;
305
306 // Transfer next queued thread to the active thread list
307 lock (s_queuedThreads)
308 {
309 if (s_queuedThreads.Count > 0)
310 {
311 item = s_queuedThreads.First.Value;
312 s_queuedThreads.RemoveFirst();
313 }
314
315 if ((object)item != null)
316 {
317 // Capture current thread (this is owned by .NET ThreadPool)
318 item.Thread = Thread.CurrentThread;
319 item.Status = ThreadStatus.Started;
320 s_activeThreads.AddLast(item);
321 }
322 }
323
324 return item;
325 }
326
327 /// <summary>
328 /// Returns a descriptive status of all queued and active mananged threads
329 /// </summary>
330 public static string ActiveThreadStatus
331 {
332 get
333 {
334 System.Text.StringBuilder status = new StringBuilder();
335 ManagedThread[] items = QueuedThreads;
336 int index = 0;
337
338 // Managed Thread Count: 1
339 //
340 // Thread 1 - Completed in 25 seconds
341 // Type: Standard Thread
342 // Name: TVASPDC.Service.CalculatedMeasurementInitialization.Initialize()
343
344 status.AppendFormat("Managed Thread Count: {0}{1}", items.Length, Environment.NewLine);
345 status.AppendLine();
346
347 foreach (ManagedThread item in items)
348 {
349 index++;
350 status.AppendFormat("Thread {0} - {1}{2}", index, ThreadStatusText(item), Environment.NewLine);
351 status.AppendFormat(" Type: {0}{1}", Enum.GetName(typeof(ThreadType), item.Type), Environment.NewLine);
352 status.AppendFormat(" Name: {0}{1}", item.Name, Environment.NewLine);
353 status.AppendLine();
354 }
355
356 return status.ToString();
357 }
358 }
359
360 private static string ThreadStatusText(ManagedThread item)
361 {
362 string runtime = item.RunTime.ToString();
363
364 switch (item.Status)
365 {
366 case ThreadStatus.Unstarted:
367 return "Not Started";
368 case ThreadStatus.Queued:
369 return "Queued";
370 case ThreadStatus.Executing:
371 return "Executing for " + runtime;
372 case ThreadStatus.Completed:
373 return "Completed in " + runtime;
374 case ThreadStatus.Aborted:
375 return "Aborted, ran for " + runtime;
376 default:
377 return "Status Unknown";
378 }
379 }
380
381 /// <summary>
382 /// Returns a copy of the currently queued and active threads
383 /// </summary>
384 public static ManagedThread[] QueuedThreads
385 {
386 get
387 {
388 List<ManagedThread> threads = new List<ManagedThread>();
389
390 lock (s_queuedThreads)
391 {
392 threads.AddRange(s_queuedThreads);
393 threads.AddRange(s_activeThreads);
394 }
395
396 return threads.ToArray();
397 }
398 }
399
400 /// <summary>
401 /// Removes a queued thread from thread pool if still queued, if allowAbort is True
402 /// aborts the thread if executing (standard or queued)
403 /// </summary>
404 /// <param name="item">Thread to cancel</param>
405 /// <param name="allowAbort">Set to True to abort thread if executing</param>
406 /// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted.</param>
407 public static void Cancel(ManagedThread item, bool allowAbort, object stateInfo)
408 {
409 if ((object)item == null)
410 throw new ArgumentNullException("item");
411
412 LinkedListNode<ManagedThread> node;
413
414 lock (s_queuedThreads)
415 {
416 // Change thread status to aborted
417 item.Status = ThreadStatus.Aborted;
418
419 // See if item is still queued for execution in thread pool
420 node = s_queuedThreads.Find(item);
421
422 // Handle abort or dequeue
423 if ((object)node == null)
424 {
425 if (allowAbort)
426 {
427 // Started items may be aborted, even if running in thread pool
428 if ((object)stateInfo == null)
429 item.Thread.Abort();
430 else
431 item.Thread.Abort(stateInfo);
432 }
433 }
434 else
435 {
436 // Remove item from queue if queued thread has yet to start
437 s_queuedThreads.Remove(node);
438 }
439 }
440 }
441 }
442}
Source/Libraries/GSF.Core/Threading/NamespaceDoc.cs+244−0
@@ -0,0 +1,244 @@
1//*******************************************************************************************************
2// NamespaceDoc.cs - Gbtc
3//
4// Tennessee Valley Authority, 2009
5// No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8//
9// Code Modification History:
10// -----------------------------------------------------------------------------------------------------
11// 09/29/2009 - Pinal C. Patel
12// Generated original version of source code.
13//
14//*******************************************************************************************************
15
16#region [ TVA Open Source Agreement ]
17/*
18
19 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
20 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
21 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
22 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
23 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
24 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
25 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
26
27 Original Software Designation: openPDC
28 Original Software Title: The GSF Open Source Phasor Data Concentrator
29 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
30 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
31
32 1. DEFINITIONS
33
34 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
35 that makes a Modification.
36
37 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
38 the use or sale of its Modification alone or when combined with the Subject Software.
39
40 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
41 image, or any other device.
42
43 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
44 another.
45
46 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
47 software separate from the Subject Software that is not governed by the terms of this Agreement.
48
49 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
50 structure of either the Original Software or Subject Software, and includes derivative works, as that
51 term is defined in the Copyright Statute, 17 USC § 101. However, the act of including Subject Software
52 as part of a Larger Work does not in and of itself constitute a Modification.
53
54 G. "Original Software" means the computer software first released under this Agreement by Government
55 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
56
57 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
58 Contributors.
59
60 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
61
62 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
63
64 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
65
66 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
67
68 M. "Use" means the application or employment of the Subject Software for any purpose.
69
70 2. GRANT OF RIGHTS
71
72 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
73 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
74 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
75 the Subject Software:
76
77 1. Use
78
79 2. Distribution
80
81 3. Reproduction
82
83 4. Modification
84
85 5. Redistribution
86
87 6. Display
88
89 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
90 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
91 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
92 pertaining to the Subject Software:
93
94 1. Use
95
96 2. Distribution
97
98 3. Reproduction
99
100 4. Sale
101
102 5. Offer for Sale
103
104 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
105 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
106 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
107 any other combinations that include a Modification.
108
109 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
110 Such sublicense must be under the same terms and conditions of this Agreement.
111
112 3. OBLIGATIONS OF RECIPIENT
113
114 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
115 additions covered under paragraph 3H.
116
117 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
118 must be included with each copy of the Subject Software; and
119
120 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
121 Recipient must also make the source code freely available, and must provide with each copy of the
122 Subject Software information on how to obtain the source code in a reasonable manner on or through a
123 medium customarily used for software exchange.
124
125 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
126 Software:
127
128 No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
129
130 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
131 must identify itself as the originator of its Modification in a manner that reasonably allows
132 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
133 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
134 made and the date of the alterations, identifies Contributor as originator of the alterations, and
135 consents to characterization of the alterations as a Modification, for example, by including a
136 statement that the Modification is derived, directly or indirectly, from Original Software provided by
137 Government Agency. Once consent is granted, it may not thereafter be revoked.
138
139 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
140 been added to the Subject Software, a Recipient may not remove it without the express permission of
141 the Contributor who added the notice.
142
143 E. A Recipient may not make any representation in the Subject Software or in any promotional,
144 advertising or other material that may be construed as an endorsement by Government Agency or by any
145 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
146 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
147
148 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
149 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
150 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
151 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
152 requested that the Recipient inform Government Agency at the web site provided above how to access the
153 Modification.
154
155 G. Each Contributor represents that that its Modification does not violate any existing agreements,
156 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
157 conveyed by this Agreement.
158
159 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
160 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
161 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
162 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
163 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
164 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
165 indemnity and/or liability offered by such Recipient.
166
167 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
168 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
169 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
170 is subject to this Agreement.
171
172 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
173 any goods or technical data from the United States may require some form of export license from the
174 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
175 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
176 required, it shall be issued. Nothing granted herein provides any such export license.
177
178 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
179
180 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
181 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
182 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
183 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
184 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
185 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
186 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
187 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
188 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
189 "AS IS."
190
191 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
192 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
193 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
194 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
195 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
196 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
197 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
198 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
199 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
200 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
201
202 5. GENERAL TERMS
203
204 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
205 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
206 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
207 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
208 Software properly granted by the breaching Recipient shall survive any such termination of this
209 Agreement.
210
211 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
212 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
213
214 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
215 including, but not limited to, determining the validity of this Agreement, the meaning of its
216 provisions and the rights, obligations and remedies of the parties.
217
218 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
219 parties relating to release of the Subject Software and may not be superseded, modified or amended
220 except by further written agreement duly executed by the parties.
221
222 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
223 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
224 Recipient hereby agrees to all terms and conditions herein.
225
226 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
227 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
228
229*/
230#endregion
231
232using System.Runtime.CompilerServices;
233
234namespace GSF.Threading
235{
236 /// <summary>
237 /// Contains classes used to define managed threads that can be used for debugging threads by providing
238 /// automatic tracking, total thread runtime and the ability to run threads in alternate execution contexts.
239 /// </summary>
240 [CompilerGenerated()]
241 class NamespaceDoc
242 {
243 }
244}
Source/Libraries/GSF.Core/Threading/ReaderWriterSpinLock.cs+396−0
@@ -0,0 +1,396 @@
1//*******************************************************************************************************
2// ReaderWriterSpinLock.cs - Gbtc
3//
4// Tennessee Valley Authority, 2011
5// No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
6//
7// This software is made freely available under the TVA Open Source Agreement (see below).
8// Code in this file licensed to GSF under one or more contributor license agreements listed below.
9//
10// Code Modification History:
11// -----------------------------------------------------------------------------------------------------
12// 03/21/2011 - Ritchie
13// Generated original version of source code based on Joe Duffy's Weblog articles:
14// "A single-word reader/writer spin lock", January 29, 2009
15// http://www.bluebytesoftware.com/blog/2009/01/30/ASinglewordReaderwriterSpinLock.aspx
16// "A more scalable reader/writer lock, and a bit less harsh consideration of the idea", February 20, 2009
17// http://www.bluebytesoftware.com/blog/2009/02/21/AMoreScalableReaderwriterLockAndABitLessHarshConsiderationOfTheIdea.aspx
18//
19//*******************************************************************************************************
20
21#region [ TVA Open Source Agreement ]
22/*
23
24 THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE,REPRODUCTION, DISTRIBUTION,
25 MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE
26 TENNESSEE VALLEY AUTHORITY, A CORPORATE AGENCY AND INSTRUMENTALITY OF THE UNITED STATES GOVERNMENT
27 ("GOVERNMENT AGENCY"). GOVERNMENT AGENCY IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT
28 DISTRIBUTIONS OR REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES,
29 MODIFIES OR REDISTRIBUTES THE SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT
30 ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.
31
32 Original Software Designation: openPDC
33 Original Software Title: The GSF Open Source Phasor Data Concentrator
34 User Registration Requested. Please Visit https://naspi.tva.com/Registration/
35 Point of Contact for Original Software: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>
36
37 1. DEFINITIONS
38
39 A. "Contributor" means Government Agency, as the developer of the Original Software, and any entity
40 that makes a Modification.
41
42 B. "Covered Patents" mean patent claims licensable by a Contributor that are necessarily infringed by
43 the use or sale of its Modification alone or when combined with the Subject Software.
44
45 C. "Display" means the showing of a copy of the Subject Software, either directly or by means of an
46 image, or any other device.
47
48 D. "Distribution" means conveyance or transfer of the Subject Software, regardless of means, to
49 another.
50
51 E. "Larger Work" means computer software that combines Subject Software, or portions thereof, with
52 software separate from the Subject Software that is not governed by the terms of this Agreement.
53
54 F. "Modification" means any alteration of, including addition to or deletion from, the substance or
55 structure of either the Original Software or Subject Software, and includes derivative works, as that
56 term is defined in the Copyright Statute, 17 USC § 101. However, the act of including Subject Software
57 as part of a Larger Work does not in and of itself constitute a Modification.
58
59 G. "Original Software" means the computer software first released under this Agreement by Government
60 Agency entitled openPDC, including source code, object code and accompanying documentation, if any.
61
62 H. "Recipient" means anyone who acquires the Subject Software under this Agreement, including all
63 Contributors.
64
65 I. "Redistribution" means Distribution of the Subject Software after a Modification has been made.
66
67 J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
68
69 K. "Sale" means the exchange of the Subject Software for money or equivalent value.
70
71 L. "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
72
73 M. "Use" means the application or employment of the Subject Software for any purpose.
74
75 2. GRANT OF RIGHTS
76
77 A. Under Non-Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor,
78 with respect to its own contribution to the Subject Software, hereby grants to each Recipient a
79 non-exclusive, world-wide, royalty-free license to engage in the following activities pertaining to
80 the Subject Software:
81
82 1. Use
83
84 2. Distribution
85
86 3. Reproduction
87
88 4. Modification
89
90 5. Redistribution
91
92 6. Display
93
94 B. Under Patent Rights: Subject to the terms and conditions of this Agreement, each Contributor, with
95 respect to its own contribution to the Subject Software, hereby grants to each Recipient under Covered
96 Patents a non-exclusive, world-wide, royalty-free license to engage in the following activities
97 pertaining to the Subject Software:
98
99 1. Use
100
101 2. Distribution
102
103 3. Reproduction
104
105 4. Sale
106
107 5. Offer for Sale
108
109 C. The rights granted under Paragraph B. also apply to the combination of a Contributor's Modification
110 and the Subject Software if, at the time the Modification is added by the Contributor, the addition of
111 such Modification causes the combination to be covered by the Covered Patents. It does not apply to
112 any other combinations that include a Modification.
113
114 D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those same rights.
115 Such sublicense must be under the same terms and conditions of this Agreement.
116
117 3. OBLIGATIONS OF RECIPIENT
118
119 A. Distribution or Redistribution of the Subject Software must be made under this Agreement except for
120 additions covered under paragraph 3H.
121
122 1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of this Agreement
123 must be included with each copy of the Subject Software; and
124
125 2. If Recipient distributes or redistributes the Subject Software in any form other than source code,
126 Recipient must also make the source code freely available, and must provide with each copy of the
127 Subject Software information on how to obtain the source code in a reasonable manner on or through a
128 medium customarily used for software exchange.
129
130 B. Each Recipient must ensure that the following copyright notice appears prominently in the Subject
131 Software:
132
133 No copyright is claimed pursuant to 17 USC § 105. All Other Rights Reserved.
134
135 C. Each Contributor must characterize its alteration of the Subject Software as a Modification and
136 must identify itself as the originator of its Modification in a manner that reasonably allows
137 subsequent Recipients to identify the originator of the Modification. In fulfillment of these
138 requirements, Contributor must include a file (e.g., a change log file) that describes the alterations
139 made and the date of the alterations, identifies Contributor as originator of the alterations, and
140 consents to characterization of the alterations as a Modification, for example, by including a
141 statement that the Modification is derived, directly or indirectly, from Original Software provided by
142 Government Agency. Once consent is granted, it may not thereafter be revoked.
143
144 D. A Contributor may add its own copyright notice to the Subject Software. Once a copyright notice has
145 been added to the Subject Software, a Recipient may not remove it without the express permission of
146 the Contributor who added the notice.
147
148 E. A Recipient may not make any representation in the Subject Software or in any promotional,
149 advertising or other material that may be construed as an endorsement by Government Agency or by any
150 prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial
151 advantage by the fact of Government Agency's or a prior Recipient's participation in this Agreement.
152
153 F. In an effort to track usage and maintain accurate records of the Subject Software, each Recipient,
154 upon receipt of the Subject Software, is requested to register with Government Agency by visiting the
155 following website: https://naspi.tva.com/Registration/. Recipient's name and personal information
156 shall be used for statistical purposes only. Once a Recipient makes a Modification available, it is
157 requested that the Recipient inform Government Agency at the web site provided above how to access the
158 Modification.
159
160 G. Each Contributor represents that that its Modification does not violate any existing agreements,
161 regulations, statutes or rules, and further that Contributor has sufficient rights to grant the rights
162 conveyed by this Agreement.
163
164 H. A Recipient may choose to offer, and to charge a fee for, warranty, support, indemnity and/or
165 liability obligations to one or more other Recipients of the Subject Software. A Recipient may do so,
166 however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a
167 Recipient must make it absolutely clear that any such warranty, support, indemnity and/or liability
168 obligation is offered by that Recipient alone. Further, such Recipient agrees to indemnify Government
169 Agency and every other Recipient for any liability incurred by them as a result of warranty, support,
170 indemnity and/or liability offered by such Recipient.
171
172 I. A Recipient may create a Larger Work by combining Subject Software with separate software not
173 governed by the terms of this agreement and distribute the Larger Work as a single product. In such
174 case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work
175 is subject to this Agreement.
176
177 J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice that export of
178 any goods or technical data from the United States may require some form of export license from the
179 U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under
180 U.S. laws. Government Agency neither represents that a license shall not be required nor that, if
181 required, it shall be issued. Nothing granted herein provides any such export license.
182
183 4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION
184
185 A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
186 EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT
187 SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
188 PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR
189 FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS
190 AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR
191 RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS
192 RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND
193 LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT
194 "AS IS."
195
196 B. Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST GOVERNMENT AGENCY, ITS
197 AGENTS, EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE
198 OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM
199 SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE
200 SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS GOVERNMENT AGENCY, ITS AGENTS,
201 EMPLOYEES, CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY
202 LAW. THE FOREGOING RELEASE AND INDEMNIFICATION SHALL APPLY EVEN IF THE LIABILITIES, DEMANDS, DAMAGES,
203 EXPENSES OR LOSSES ARE CAUSED, OCCASIONED, OR CONTRIBUTED TO BY THE NEGLIGENCE, SOLE OR CONCURRENT, OF
204 GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
205 IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
206
207 5. GENERAL TERMS
208
209 A. Termination: This Agreement and the rights granted hereunder will terminate automatically if a
210 Recipient fails to comply with these terms and conditions, and fails to cure such noncompliance within
211 thirty (30) days of becoming aware of such noncompliance. Upon termination, a Recipient agrees to
212 immediately cease use and distribution of the Subject Software. All sublicenses to the Subject
213 Software properly granted by the breaching Recipient shall survive any such termination of this
214 Agreement.
215
216 B. Severability: If any provision of this Agreement is invalid or unenforceable under applicable law,
217 it shall not affect the validity or enforceability of the remainder of the terms of this Agreement.
218
219 C. Applicable Law: This Agreement shall be subject to United States federal law only for all purposes,
220 including, but not limited to, determining the validity of this Agreement, the meaning of its
221 provisions and the rights, obligations and remedies of the parties.
222
223 D. Entire Understanding: This Agreement constitutes the entire understanding and agreement of the
224 parties relating to release of the Subject Software and may not be superseded, modified or amended
225 except by further written agreement duly executed by the parties.
226
227 E. Binding Authority: By accepting and using the Subject Software under this Agreement, a Recipient
228 affirms its authority to bind the Recipient to all terms and conditions of this Agreement and that
229 Recipient hereby agrees to all terms and conditions herein.
230
231 F. Point of Contact: Any Recipient contact with Government Agency is to be directed to the designated
232 representative as follows: J. Ritchie Carroll <mailto:jrcarrol@tva.gov>.
233
234*/
235#endregion
236
237#region [ Contributor License Agreements ]
238
239//******************************************************************************************************
240//
241// Copyright © 2011, Grid Protection Alliance. All Rights Reserved.
242//
243// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
244// not use this file except in compliance with the License. You may obtain a copy of the License at:
245//
246// http://www.opensource.org/licenses/eclipse-1.0.php
247//
248// Unless agreed to in writing, the subject software distributed under the License is distributed on an
249// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
250// License for the specific language governing permissions and limitations.
251//
252//******************************************************************************************************
253
254#endregion
255
256using System;
257using System.Runtime.InteropServices;
258using System.Threading;
259
260// We use plenty of interlocked operations on volatile fields below. Safe.
261#pragma warning disable 0420
262
263namespace GSF.Threading
264{
265 /// <summary>
266 /// Represents a fast, lightweight reader/writer lock that uses spinning to perform locking with no thread affinity. No recursive
267 /// acquires or upgradable locks are allowed (i.e., all entered locks must be exited before entering another lock).
268 /// </summary>
269 /// <remarks>
270 /// <para>
271 /// <see cref="ReaderWriterSpinLock"/> uses a single word of memory and only spins when contention arises so no events are necessary.
272 /// </para>
273 /// <para>
274 /// This reader/writer lock uses <see cref="SpinWait"/> to spin the CPU instead of engaging event based locking. As a result it
275 /// should only be used in cases where lock times are expected to be very small, reads are very frequent and writes are rare.
276 /// If hold times for write locks can be lengthy, it will be better to use <see cref="ReaderWriterLockSlim"/> instead to avoid
277 /// unnecessary CPU utilization due to spinning incurred by waiting reads.
278 /// </para>
279 /// </remarks>
280 public class ReaderWriterSpinLock
281 {
282 #region [ Members ]
283
284 // Nested Types
285 [StructLayout(LayoutKind.Sequential, Size = 128)]
286 struct ReadEntry
287 {
288 internal volatile int m_taken;
289 }
290
291 // Fields
292 private volatile int m_writer;
293 private volatile ReadEntry[] m_readers = new ReadEntry[Environment.ProcessorCount * 16];
294
295 #endregion
296
297 #region [ Properties ]
298
299 private int ReadLockIndex
300 {
301 get
302 {
303 return Thread.CurrentThread.ManagedThreadId % m_readers.Length;
304 }
305 }
306
307 #endregion
308
309 #region [ Methods ]
310
311 /// <summary>
312 /// Enters the lock in write mode.
313 /// </summary>
314 /// <remarks>
315 /// Upon successful aquistion of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>.
316 /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/>.
317 /// </remarks>
318 public void EnterWriteLock()
319 {
320 SpinWait sw = new SpinWait();
321
322 while (true)
323 {
324 if (m_writer == 0 && Interlocked.Exchange(ref m_writer, 1) == 0)
325 {
326 // We now hold the write lock, and prevent new readers -
327 // but we must ensure no readers exist before proceeding.
328 for (int i = 0; i < m_readers.Length; i++)
329 {
330 while (m_readers[i].m_taken != 0)
331 sw.SpinOnce();
332 }
333
334 break;
335 }
336
337 // We failed to take the write lock; wait a bit and retry.
338 sw.SpinOnce();
339 }
340 }
341
342 /// <summary>
343 /// Exits write mode.
344 /// </summary>
345 public void ExitWriteLock()
346 {
347 // No need for a CAS.
348 m_writer = 0;
349 }
350
351 /// <summary>
352 /// Enters the lock in read mode.
353 /// </summary>
354 /// <remarks>
355 /// Upon successful aquistion of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>.
356 /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/>.
357 /// </remarks>
358 public void EnterReadLock()
359 {
360 SpinWait sw = new SpinWait();
361 int tid = ReadLockIndex;
362
363 // Wait until there are no writers.
364 while (true)
365 {
366 while (m_writer == 1)
367 sw.SpinOnce();
368
369 // Try to take the read lock.
370 Interlocked.Increment(ref m_readers[tid].m_taken);
371
372 if (m_writer == 0)
373 {
374 // Success, no writer, proceed.
375 break;
376 }
377
378 // Back off, to let the writer go through.
379 Interlocked.Decrement(ref m_readers[tid].m_taken);
380 }
381 }
382
383 /// <summary>
384 /// Exits read mode.
385 /// </summary>
386 /// <exception cref="InvalidOperationException">Cannot exit read lock when there are no readers.</exception>
387 public void ExitReadLock()
388 {
389 // Just note that the current reader has left the lock.
390 Interlocked.Decrement(ref m_readers[ReadLockIndex].m_taken);
391 }
392
393 #endregion
394 }
395}
396

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t