Thread.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. //
  2. // System.Threading.Thread.cs
  3. //
  4. // Author:
  5. // Dick Porter ([email protected])
  6. //
  7. // (C) Ximian, Inc. http://www.ximian.com
  8. // Copyright (C) 2004 Novell (http://www.novell.com)
  9. //
  10. //
  11. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System.Runtime.Remoting.Contexts;
  33. using System.Runtime.Serialization;
  34. using System.Runtime.Serialization.Formatters.Binary;
  35. using System.Security.Permissions;
  36. using System.Security.Principal;
  37. using System.Globalization;
  38. using System.Runtime.CompilerServices;
  39. using System.IO;
  40. using System.Collections;
  41. using System.Security;
  42. #if NET_2_0
  43. using System.Runtime.ConstrainedExecution;
  44. using System.Runtime.InteropServices;
  45. #endif
  46. namespace System.Threading
  47. {
  48. public sealed class Thread
  49. {
  50. #region Sync with metadata/object-internals.h
  51. int lock_thread_id;
  52. // stores a thread handle
  53. private IntPtr system_thread_handle;
  54. private IntPtr culture_info;
  55. private IntPtr ui_culture_info;
  56. private bool threadpool_thread;
  57. /* accessed only from unmanaged code */
  58. private IntPtr name;
  59. private int name_len;
  60. private ThreadState state = ThreadState.Unstarted;
  61. private object abort_exc;
  62. internal object abort_state;
  63. /* thread_id is only accessed from unmanaged code */
  64. private int thread_id;
  65. /* start_notify is used by the runtime to signal that Start()
  66. * is ok to return
  67. */
  68. private IntPtr start_notify;
  69. private IntPtr stack_ptr;
  70. private IntPtr static_data;
  71. private IntPtr jit_data;
  72. private IntPtr lock_data;
  73. IntPtr unused1;
  74. IntPtr unused2;
  75. int stack_size;
  76. object start_obj;
  77. private IntPtr appdomain_refs;
  78. private bool interruption_requested;
  79. private IntPtr suspend_event;
  80. private IntPtr resume_event;
  81. private object synch_lock = new Object();
  82. private IntPtr serialized_culture_info;
  83. private int serialized_culture_info_len;
  84. private IntPtr serialized_ui_culture_info;
  85. private int serialized_ui_culture_info_len;
  86. #endregion
  87. // can be both a ThreadSart and a ParameterizedThreadStart
  88. private MulticastDelegate threadstart;
  89. private string thread_name=null;
  90. private IPrincipal _principal;
  91. private CompressedStack _stack;
  92. public static Context CurrentContext {
  93. [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
  94. get {
  95. return(AppDomain.InternalGetContext ());
  96. }
  97. }
  98. public static IPrincipal CurrentPrincipal {
  99. get {
  100. IPrincipal p = null;
  101. Thread th = CurrentThread;
  102. lock (th) {
  103. p = th._principal;
  104. if (p == null) {
  105. p = GetDomain ().DefaultPrincipal;
  106. th._principal = p;
  107. }
  108. }
  109. return p;
  110. }
  111. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  112. set {
  113. CurrentThread._principal = value;
  114. }
  115. }
  116. // Looks up the object associated with the current thread
  117. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  118. private extern static Thread CurrentThread_internal();
  119. public static Thread CurrentThread {
  120. #if NET_2_0
  121. [ReliabilityContract (Consistency.WillNotCorruptState, CER.MayFail)]
  122. #endif
  123. get {
  124. return(CurrentThread_internal());
  125. }
  126. }
  127. internal static int CurrentThreadId {
  128. get {
  129. return CurrentThread.thread_id;
  130. }
  131. }
  132. // Looks up the slot hash for the current thread
  133. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  134. private extern static Hashtable SlotHash_lookup();
  135. // Stores the slot hash for the current thread
  136. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  137. private extern static void SlotHash_store(Hashtable slothash);
  138. private static Hashtable GetTLSSlotHash() {
  139. Hashtable slothash=SlotHash_lookup();
  140. if(slothash==null) {
  141. // Not synchronised, because this is
  142. // thread specific anyway.
  143. slothash=new Hashtable();
  144. SlotHash_store(slothash);
  145. }
  146. return(slothash);
  147. }
  148. internal static object ResetDataStoreStatus () {
  149. Hashtable slothash=SlotHash_lookup();
  150. SlotHash_store(null);
  151. return slothash;
  152. }
  153. internal static void RestoreDataStoreStatus (object data) {
  154. SlotHash_store((Hashtable)data);
  155. }
  156. public static LocalDataStoreSlot AllocateDataSlot() {
  157. LocalDataStoreSlot slot = new LocalDataStoreSlot();
  158. return(slot);
  159. }
  160. // Stores a hash keyed by strings of LocalDataStoreSlot objects
  161. static Hashtable datastorehash;
  162. private static object datastore_lock = new object ();
  163. private static void InitDataStoreHash () {
  164. lock (datastore_lock) {
  165. if (datastorehash == null) {
  166. datastorehash = Hashtable.Synchronized(new Hashtable());
  167. }
  168. }
  169. }
  170. public static LocalDataStoreSlot AllocateNamedDataSlot(string name) {
  171. lock (datastore_lock) {
  172. if (datastorehash == null)
  173. InitDataStoreHash ();
  174. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash[name];
  175. if(slot!=null) {
  176. // This exception isnt documented (of
  177. // course) but .net throws it
  178. throw new ArgumentException("Named data slot already added");
  179. }
  180. slot = new LocalDataStoreSlot();
  181. datastorehash.Add(name, slot);
  182. return(slot);
  183. }
  184. }
  185. public static void FreeNamedDataSlot(string name) {
  186. lock (datastore_lock) {
  187. if (datastorehash == null)
  188. InitDataStoreHash ();
  189. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  190. if(slot!=null) {
  191. datastorehash.Remove(slot);
  192. }
  193. }
  194. }
  195. public static object GetData(LocalDataStoreSlot slot) {
  196. Hashtable slothash=GetTLSSlotHash();
  197. return(slothash[slot]);
  198. }
  199. public static AppDomain GetDomain() {
  200. return AppDomain.CurrentDomain;
  201. }
  202. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  203. public extern static int GetDomainID();
  204. public static LocalDataStoreSlot GetNamedDataSlot(string name) {
  205. lock (datastore_lock) {
  206. if (datastorehash == null)
  207. InitDataStoreHash ();
  208. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  209. if(slot==null) {
  210. slot=AllocateNamedDataSlot(name);
  211. }
  212. return(slot);
  213. }
  214. }
  215. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  216. private extern static void ResetAbort_internal();
  217. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  218. public static void ResetAbort ()
  219. {
  220. ResetAbort_internal ();
  221. }
  222. public static void SetData(LocalDataStoreSlot slot,
  223. object data) {
  224. Hashtable slothash=GetTLSSlotHash();
  225. if(slothash.Contains(slot)) {
  226. slothash.Remove(slot);
  227. }
  228. slothash.Add(slot, data);
  229. }
  230. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  231. private extern static void Sleep_internal(int ms);
  232. public static void Sleep(int millisecondsTimeout) {
  233. if((millisecondsTimeout<0) && (millisecondsTimeout != Timeout.Infinite)) {
  234. throw new ArgumentException("Negative timeout");
  235. }
  236. Sleep_internal(millisecondsTimeout);
  237. }
  238. public static void Sleep(TimeSpan timeout) {
  239. // LAMESPEC: says to throw ArgumentException too
  240. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  241. if(ms < 0 || ms > Int32.MaxValue) {
  242. throw new ArgumentOutOfRangeException("Timeout out of range");
  243. }
  244. Sleep_internal(ms);
  245. }
  246. // Returns the system thread handle
  247. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  248. private extern IntPtr Thread_internal (MulticastDelegate start);
  249. public Thread(ThreadStart start) {
  250. if(start==null) {
  251. throw new ArgumentNullException("Null ThreadStart");
  252. }
  253. threadstart=start;
  254. }
  255. [MonoTODO]
  256. #if NET_2_0
  257. [Obsolete ("")]
  258. #endif
  259. public ApartmentState ApartmentState {
  260. get {
  261. return(ApartmentState.Unknown);
  262. }
  263. set {
  264. }
  265. }
  266. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  267. private static extern int current_lcid ();
  268. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  269. private extern CultureInfo GetCachedCurrentCulture ();
  270. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  271. private extern byte[] GetSerializedCurrentCulture ();
  272. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  273. private extern void SetCachedCurrentCulture (CultureInfo culture);
  274. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  275. private extern void SetSerializedCurrentCulture (byte[] culture);
  276. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  277. private extern CultureInfo GetCachedCurrentUICulture ();
  278. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  279. private extern byte[] GetSerializedCurrentUICulture ();
  280. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  281. private extern void SetCachedCurrentUICulture (CultureInfo culture);
  282. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  283. private extern void SetSerializedCurrentUICulture (byte[] culture);
  284. /* If the current_lcid() isn't known by CultureInfo,
  285. * it will throw an exception which may cause
  286. * String.Concat to try and recursively look up the
  287. * CurrentCulture, which will throw an exception, etc.
  288. * Use a boolean to short-circuit this scenario.
  289. */
  290. private static bool in_currentculture=false;
  291. /*
  292. * Thread objects are shared between appdomains, and CurrentCulture
  293. * should always return an object in the calling appdomain. See bug
  294. * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
  295. * This is hard to implement correctly and efficiently, so the current
  296. * implementation is not perfect: changes made in one appdomain to the
  297. * state of the current cultureinfo object are not visible to other
  298. * appdomains.
  299. */
  300. public CultureInfo CurrentCulture {
  301. get {
  302. if (in_currentculture)
  303. /* Bail out */
  304. return CultureInfo.InvariantCulture;
  305. CultureInfo culture = GetCachedCurrentCulture ();
  306. if (culture != null)
  307. return culture;
  308. byte[] arr = GetSerializedCurrentCulture ();
  309. if (arr == null) {
  310. lock (typeof (Thread)) {
  311. in_currentculture=true;
  312. culture = CultureInfo.ConstructCurrentCulture ();
  313. //
  314. // Don't serialize the culture in this case to avoid
  315. // initializing the serialization infrastructure in the
  316. // common case when the culture is not set explicitly.
  317. //
  318. SetCachedCurrentCulture (culture);
  319. in_currentculture = false;
  320. return culture;
  321. }
  322. }
  323. /*
  324. * No cultureinfo object exists for this domain, so create one
  325. * by deserializing the serialized form.
  326. */
  327. in_currentculture = true;
  328. try {
  329. BinaryFormatter bf = new BinaryFormatter ();
  330. MemoryStream ms = new MemoryStream (arr);
  331. culture = (CultureInfo)bf.Deserialize (ms);
  332. SetCachedCurrentCulture (culture);
  333. }
  334. finally {
  335. in_currentculture = false;
  336. }
  337. return culture;
  338. }
  339. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  340. set {
  341. in_currentculture = true;
  342. try {
  343. BinaryFormatter bf = new BinaryFormatter();
  344. MemoryStream ms = new MemoryStream ();
  345. bf.Serialize (ms, value);
  346. SetCachedCurrentCulture (value);
  347. SetSerializedCurrentCulture (ms.GetBuffer ());
  348. }
  349. finally {
  350. in_currentculture = false;
  351. }
  352. }
  353. }
  354. public CultureInfo CurrentUICulture {
  355. get {
  356. if (in_currentculture)
  357. /* Bail out */
  358. return CultureInfo.InvariantCulture;
  359. CultureInfo culture = GetCachedCurrentUICulture ();
  360. if (culture != null)
  361. return culture;
  362. byte[] arr = GetSerializedCurrentUICulture ();
  363. if (arr == null) {
  364. lock (typeof (Thread)) {
  365. in_currentculture=true;
  366. /* We don't
  367. * distinguish
  368. * between
  369. * System and
  370. * UI cultures
  371. */
  372. culture = CultureInfo.ConstructCurrentUICulture ();
  373. //
  374. // Don't serialize the culture in this case to avoid
  375. // initializing the serialization infrastructure in the
  376. // common case when the culture is not set explicitly.
  377. //
  378. SetCachedCurrentUICulture (culture);
  379. in_currentculture = false;
  380. return culture;
  381. }
  382. }
  383. /*
  384. * No cultureinfo object exists for this domain, so create one
  385. * by deserializing the serialized form.
  386. */
  387. in_currentculture = true;
  388. try {
  389. BinaryFormatter bf = new BinaryFormatter ();
  390. MemoryStream ms = new MemoryStream (arr);
  391. culture = (CultureInfo)bf.Deserialize (ms);
  392. SetCachedCurrentUICulture (culture);
  393. }
  394. finally {
  395. in_currentculture = false;
  396. }
  397. return culture;
  398. }
  399. set {
  400. in_currentculture = true;
  401. try {
  402. BinaryFormatter bf = new BinaryFormatter();
  403. MemoryStream ms = new MemoryStream ();
  404. bf.Serialize (ms, value);
  405. SetCachedCurrentUICulture (value);
  406. SetSerializedCurrentUICulture (ms.GetBuffer ());
  407. }
  408. finally {
  409. in_currentculture = false;
  410. }
  411. }
  412. }
  413. public bool IsThreadPoolThread {
  414. get {
  415. return IsThreadPoolThreadInternal;
  416. }
  417. }
  418. internal bool IsThreadPoolThreadInternal {
  419. get {
  420. return threadpool_thread;
  421. }
  422. set {
  423. threadpool_thread = value;
  424. }
  425. }
  426. public bool IsAlive {
  427. get {
  428. ThreadState curstate=state;
  429. if((curstate & ThreadState.Aborted) != 0 ||
  430. (curstate & ThreadState.Stopped) != 0 ||
  431. (curstate & ThreadState.Unstarted) != 0) {
  432. return(false);
  433. } else {
  434. return(true);
  435. }
  436. }
  437. }
  438. public bool IsBackground {
  439. get {
  440. if((state & ThreadState.Background) != 0) {
  441. return(true);
  442. } else {
  443. return(false);
  444. }
  445. }
  446. set {
  447. if(value==true) {
  448. set_state(ThreadState.Background);
  449. } else {
  450. clr_state(ThreadState.Background);
  451. }
  452. }
  453. }
  454. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  455. private extern string GetName_internal ();
  456. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  457. private extern void SetName_internal (String name);
  458. /*
  459. * The thread name must be shared by appdomains, so it is stored in
  460. * unmanaged code.
  461. */
  462. public string Name {
  463. get {
  464. return GetName_internal ();
  465. }
  466. set {
  467. lock (synch_lock) {
  468. if(Name!=null) {
  469. throw new InvalidOperationException ("Thread.Name can only be set once.");
  470. }
  471. SetName_internal (value);
  472. }
  473. }
  474. }
  475. [MonoTODO]
  476. public ThreadPriority Priority {
  477. get {
  478. return(ThreadPriority.Lowest);
  479. }
  480. set {
  481. }
  482. }
  483. public ThreadState ThreadState {
  484. get {
  485. return(state);
  486. }
  487. }
  488. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  489. private extern void Abort_internal (object stateInfo);
  490. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  491. public void Abort ()
  492. {
  493. Abort_internal (null);
  494. }
  495. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  496. public void Abort (object stateInfo)
  497. {
  498. Abort_internal (stateInfo);
  499. }
  500. [MonoTODO]
  501. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  502. public void Interrupt ()
  503. {
  504. }
  505. // The current thread joins with 'this'. Set ms to 0 to block
  506. // until this actually exits.
  507. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  508. private extern bool Join_internal(int ms, IntPtr handle);
  509. public void Join() {
  510. if((state & ThreadState.Unstarted) != 0) {
  511. throw new ThreadStateException("Thread has not been started");
  512. }
  513. Join_internal(Timeout.Infinite, system_thread_handle);
  514. }
  515. public bool Join(int millisecondsTimeout) {
  516. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  517. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  518. if((state & ThreadState.Unstarted) != 0) {
  519. throw new ThreadStateException("Thread has not been started");
  520. }
  521. return Join_internal(millisecondsTimeout, system_thread_handle);
  522. }
  523. public bool Join(TimeSpan timeout) {
  524. // LAMESPEC: says to throw ArgumentException too
  525. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  526. if(ms < 0 || ms > Int32.MaxValue) {
  527. throw new ArgumentOutOfRangeException("timeout out of range");
  528. }
  529. if((state & ThreadState.Unstarted) != 0) {
  530. throw new ThreadStateException("Thread has not been started");
  531. }
  532. return Join_internal(ms, system_thread_handle);
  533. }
  534. #if NET_1_1
  535. [MonoTODO ("seems required for multi-processors systems like Itanium")]
  536. public static void MemoryBarrier ()
  537. {
  538. // Will be implemented when we support Itanium
  539. }
  540. #endif
  541. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  542. private extern void Resume_internal();
  543. #if NET_2_0
  544. [Obsolete ("")]
  545. #endif
  546. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  547. public void Resume ()
  548. {
  549. if ((state & ThreadState.Unstarted) != 0 || !IsAlive ||
  550. ((state & ThreadState.Suspended) == 0 && (state & ThreadState.SuspendRequested) == 0))
  551. {
  552. throw new ThreadStateException("Thread has not been started, or is dead");
  553. }
  554. Resume_internal ();
  555. }
  556. [MonoTODO]
  557. public static void SpinWait (int iterations)
  558. {
  559. throw new NotImplementedException ();
  560. }
  561. // Launches the thread
  562. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  563. private extern void Start_internal(IntPtr handle);
  564. public void Start() {
  565. lock(synch_lock) {
  566. if((state & ThreadState.Unstarted) == 0) {
  567. throw new ThreadStateException("Thread has already been started");
  568. }
  569. // Thread_internal creates the new thread, but
  570. // blocks it until Start() is called later.
  571. system_thread_handle=Thread_internal(threadstart);
  572. if (system_thread_handle == (IntPtr) 0) {
  573. throw new SystemException ("Thread creation failed");
  574. }
  575. // Launch this thread
  576. Start_internal(system_thread_handle);
  577. // Mark the thread state as Running
  578. // (which is all bits
  579. // cleared). Therefore just remove the
  580. // Unstarted bit
  581. clr_state(ThreadState.Unstarted);
  582. }
  583. }
  584. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  585. private extern void Suspend_internal();
  586. #if NET_2_0
  587. [Obsolete ("")]
  588. #endif
  589. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  590. public void Suspend ()
  591. {
  592. if((state & ThreadState.Unstarted) != 0 || !IsAlive) {
  593. throw new ThreadStateException("Thread has not been started, or is dead");
  594. }
  595. Suspend_internal ();
  596. }
  597. // Closes the system thread handle
  598. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  599. private extern void Thread_free_internal(IntPtr handle);
  600. ~Thread() {
  601. // Free up the handle
  602. if (system_thread_handle != (IntPtr) 0)
  603. Thread_free_internal(system_thread_handle);
  604. }
  605. private void set_state(ThreadState set) {
  606. lock(synch_lock) {
  607. state |= set;
  608. }
  609. }
  610. private void clr_state(ThreadState clr) {
  611. lock(synch_lock) {
  612. state &= ~clr;
  613. }
  614. }
  615. #if NET_1_1
  616. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  617. extern public static byte VolatileRead (ref byte address);
  618. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  619. extern public static double VolatileRead (ref double address);
  620. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  621. extern public static short VolatileRead (ref short address);
  622. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  623. extern public static int VolatileRead (ref int address);
  624. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  625. extern public static long VolatileRead (ref long address);
  626. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  627. extern public static IntPtr VolatileRead (ref IntPtr address);
  628. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  629. extern public static object VolatileRead (ref object address);
  630. [CLSCompliant(false)]
  631. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  632. extern public static sbyte VolatileRead (ref sbyte address);
  633. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  634. extern public static float VolatileRead (ref float address);
  635. [CLSCompliant (false)]
  636. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  637. extern public static ushort VolatileRead (ref ushort address);
  638. [CLSCompliant (false)]
  639. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  640. extern public static uint VolatileRead (ref uint address);
  641. [CLSCompliant (false)]
  642. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  643. extern public static ulong VolatileRead (ref ulong address);
  644. [CLSCompliant (false)]
  645. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  646. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  647. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  648. extern public static void VolatileWrite (ref byte address, byte value);
  649. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  650. extern public static void VolatileWrite (ref double address, double value);
  651. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  652. extern public static void VolatileWrite (ref short address, short value);
  653. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  654. extern public static void VolatileWrite (ref int address, int value);
  655. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  656. extern public static void VolatileWrite (ref long address, long value);
  657. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  658. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  659. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  660. extern public static void VolatileWrite (ref object address, object value);
  661. [CLSCompliant(false)]
  662. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  663. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  664. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  665. extern public static void VolatileWrite (ref float address, float value);
  666. [CLSCompliant (false)]
  667. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  668. extern public static void VolatileWrite (ref ushort address, ushort value);
  669. [CLSCompliant (false)]
  670. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  671. extern public static void VolatileWrite (ref uint address, uint value);
  672. [CLSCompliant (false)]
  673. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  674. extern public static void VolatileWrite (ref ulong address, ulong value);
  675. [CLSCompliant (false)]
  676. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  677. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  678. #endif
  679. #if NET_2_0
  680. public Thread (ThreadStart start, int maxStackSize)
  681. {
  682. if (start == null)
  683. throw new ArgumentNullException ("start");
  684. if (maxStackSize < 131072)
  685. throw new ArgumentException ("< 128 kb", "maxStackSize");
  686. threadstart = start;
  687. stack_size = maxStackSize;
  688. }
  689. public Thread (ParameterizedThreadStart start)
  690. {
  691. if (start == null)
  692. throw new ArgumentNullException ("start");
  693. threadstart = start;
  694. }
  695. public Thread (ParameterizedThreadStart start, int maxStackSize)
  696. {
  697. if (start == null)
  698. throw new ArgumentNullException ("start");
  699. if (maxStackSize < 131072)
  700. throw new ArgumentException ("< 128 kb", "maxStackSize");
  701. threadstart = start;
  702. stack_size = maxStackSize;
  703. }
  704. [MonoTODO]
  705. public ExecutionContext ExecutionContext {
  706. [ReliabilityContract (Consistency.WillNotCorruptState, CER.MayFail)]
  707. get { throw new NotImplementedException (); }
  708. }
  709. public int ManagedThreadId {
  710. get { return thread_id; }
  711. }
  712. [MonoTODO]
  713. [ReliabilityContract (Consistency.WillNotCorruptState, CER.MayFail)]
  714. public static void BeginCriticalRegion ()
  715. {
  716. throw new NotImplementedException ();
  717. }
  718. [MonoTODO]
  719. [ReliabilityContract (Consistency.WillNotCorruptState, CER.Success)]
  720. public static void EndCriticalRegion ()
  721. {
  722. throw new NotImplementedException ();
  723. }
  724. [MonoTODO]
  725. public static void BeginThreadAffinity ()
  726. {
  727. throw new NotImplementedException ();
  728. }
  729. [MonoTODO]
  730. public static void EndThreadAffinity ()
  731. {
  732. throw new NotImplementedException ();
  733. }
  734. [MonoTODO]
  735. public ApartmentState GetApartmentState ()
  736. {
  737. return this.ApartmentState;
  738. }
  739. [MonoTODO]
  740. public void SetApartmentState (ApartmentState state)
  741. {
  742. this.ApartmentState = state;
  743. }
  744. [MonoTODO]
  745. public bool TrySetApartmentState (ApartmentState state)
  746. {
  747. try {
  748. this.ApartmentState = state;
  749. return true;
  750. }
  751. catch (ArgumentException) {
  752. throw;
  753. }
  754. catch {
  755. return false;
  756. }
  757. }
  758. public CompressedStack GetCompressedStack ()
  759. {
  760. // Note: returns null if no CompressedStack has been set.
  761. // However CompressedStack.GetCompressedStack returns an
  762. // (empty?) CompressedStack instance.
  763. return _stack;
  764. }
  765. public void SetCompressedStack (CompressedStack stack)
  766. {
  767. _stack = stack;
  768. }
  769. [ComVisible (false)]
  770. public override int GetHashCode ()
  771. {
  772. // ??? overridden but not guaranteed to be unique ???
  773. return thread_id;
  774. }
  775. public void Start (object parameter)
  776. {
  777. start_obj = parameter;
  778. Start ();
  779. }
  780. #else
  781. internal CompressedStack GetCompressedStack ()
  782. {
  783. return _stack;
  784. }
  785. #endif
  786. }
  787. }