Thread.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. using System.Runtime.Remoting.Contexts;
  11. using System.Security.Permissions;
  12. using System.Security.Principal;
  13. using System.Globalization;
  14. using System.Runtime.CompilerServices;
  15. using System.Collections;
  16. namespace System.Threading
  17. {
  18. public sealed class Thread
  19. {
  20. #region Sync with object.h
  21. // stores a thread handle
  22. private IntPtr system_thread_handle;
  23. private CultureInfo current_culture;
  24. private CultureInfo current_ui_culture;
  25. private bool threadpool_thread;
  26. /* accessed only from unmanaged code */
  27. private IntPtr name;
  28. private int name_len;
  29. private ThreadState state = ThreadState.Unstarted;
  30. private object abort_exc;
  31. internal object abort_state;
  32. /* thread_id is only accessed from unmanaged code */
  33. private int thread_id;
  34. /* start_notify is used by the runtime to signal that Start()
  35. * is ok to return
  36. */
  37. private IntPtr start_notify;
  38. private IntPtr stack_ptr;
  39. private IntPtr static_data;
  40. private IntPtr jit_data;
  41. private IntPtr lock_data;
  42. private IntPtr appdomain_refs;
  43. private bool interruption_requested;
  44. #endregion
  45. private ThreadStart threadstart;
  46. private string thread_name=null;
  47. private IPrincipal _principal;
  48. public static Context CurrentContext {
  49. get {
  50. return(AppDomain.InternalGetContext ());
  51. }
  52. }
  53. public static IPrincipal CurrentPrincipal {
  54. get {
  55. IPrincipal p = null;
  56. lock (typeof (Thread)) {
  57. p = CurrentThread._principal;
  58. if (p == null)
  59. p = GetDomain ().DefaultPrincipal;
  60. }
  61. return p;
  62. }
  63. set {
  64. new SecurityPermission (SecurityPermissionFlag.ControlPrincipal).Demand ();
  65. CurrentThread._principal = value;
  66. }
  67. }
  68. // Looks up the object associated with the current thread
  69. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  70. private extern static Thread CurrentThread_internal();
  71. public static Thread CurrentThread {
  72. get {
  73. return(CurrentThread_internal());
  74. }
  75. }
  76. internal static int CurrentThreadId {
  77. get {
  78. return CurrentThread.thread_id;
  79. }
  80. }
  81. // Looks up the slot hash for the current thread
  82. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  83. private extern static Hashtable SlotHash_lookup();
  84. // Stores the slot hash for the current thread
  85. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  86. private extern static void SlotHash_store(Hashtable slothash);
  87. private static Hashtable GetTLSSlotHash() {
  88. Hashtable slothash=SlotHash_lookup();
  89. if(slothash==null) {
  90. // Not synchronised, because this is
  91. // thread specific anyway.
  92. slothash=new Hashtable();
  93. SlotHash_store(slothash);
  94. }
  95. return(slothash);
  96. }
  97. internal static object ResetDataStoreStatus () {
  98. Hashtable slothash=SlotHash_lookup();
  99. SlotHash_store(null);
  100. return slothash;
  101. }
  102. internal static void RestoreDataStoreStatus (object data) {
  103. SlotHash_store((Hashtable)data);
  104. }
  105. public static LocalDataStoreSlot AllocateDataSlot() {
  106. LocalDataStoreSlot slot = new LocalDataStoreSlot();
  107. return(slot);
  108. }
  109. // Stores a hash keyed by strings of LocalDataStoreSlot objects
  110. static Hashtable datastorehash;
  111. private static void InitDataStoreHash () {
  112. lock (typeof (Thread)) {
  113. if (datastorehash == null) {
  114. datastorehash = Hashtable.Synchronized(new Hashtable());
  115. }
  116. }
  117. }
  118. public static LocalDataStoreSlot AllocateNamedDataSlot(string name) {
  119. lock (typeof (Thread)) {
  120. if (datastorehash == null)
  121. InitDataStoreHash ();
  122. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash[name];
  123. if(slot!=null) {
  124. // This exception isnt documented (of
  125. // course) but .net throws it
  126. throw new ArgumentException("Named data slot already added");
  127. }
  128. slot = new LocalDataStoreSlot();
  129. datastorehash.Add(name, slot);
  130. return(slot);
  131. }
  132. }
  133. public static void FreeNamedDataSlot(string name) {
  134. lock (typeof (Thread)) {
  135. if (datastorehash == null)
  136. InitDataStoreHash ();
  137. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  138. if(slot!=null) {
  139. datastorehash.Remove(slot);
  140. }
  141. }
  142. }
  143. public static object GetData(LocalDataStoreSlot slot) {
  144. Hashtable slothash=GetTLSSlotHash();
  145. return(slothash[slot]);
  146. }
  147. public static AppDomain GetDomain() {
  148. return AppDomain.CurrentDomain;
  149. }
  150. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  151. public extern static int GetDomainID();
  152. public static LocalDataStoreSlot GetNamedDataSlot(string name) {
  153. if (datastorehash == null)
  154. InitDataStoreHash ();
  155. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  156. if(slot==null) {
  157. slot=AllocateNamedDataSlot(name);
  158. }
  159. return(slot);
  160. }
  161. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  162. private extern static void ResetAbort_internal();
  163. public static void ResetAbort()
  164. {
  165. ResetAbort_internal();
  166. }
  167. public static void SetData(LocalDataStoreSlot slot,
  168. object data) {
  169. Hashtable slothash=GetTLSSlotHash();
  170. if(slothash.Contains(slot)) {
  171. slothash.Remove(slot);
  172. }
  173. slothash.Add(slot, data);
  174. }
  175. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  176. private extern static void Sleep_internal(int ms);
  177. public static void Sleep(int millisecondsTimeout) {
  178. if((millisecondsTimeout<0) && (millisecondsTimeout != Timeout.Infinite)) {
  179. throw new ArgumentException("Negative timeout");
  180. }
  181. Thread thread=CurrentThread;
  182. thread.set_state(ThreadState.WaitSleepJoin);
  183. Sleep_internal(millisecondsTimeout);
  184. thread.clr_state(ThreadState.WaitSleepJoin);
  185. }
  186. public static void Sleep(TimeSpan timeout) {
  187. // LAMESPEC: says to throw ArgumentException too
  188. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  189. if(ms < 0 || ms > Int32.MaxValue) {
  190. throw new ArgumentOutOfRangeException("Timeout out of range");
  191. }
  192. Thread thread=CurrentThread;
  193. thread.set_state(ThreadState.WaitSleepJoin);
  194. Sleep_internal(ms);
  195. thread.clr_state(ThreadState.WaitSleepJoin);
  196. }
  197. // Returns the system thread handle
  198. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  199. private extern IntPtr Thread_internal(ThreadStart start);
  200. public Thread(ThreadStart start) {
  201. if(start==null) {
  202. throw new ArgumentNullException("Null ThreadStart");
  203. }
  204. threadstart=start;
  205. }
  206. [MonoTODO]
  207. public ApartmentState ApartmentState {
  208. get {
  209. // FIXME
  210. return(ApartmentState.Unknown);
  211. }
  212. set {
  213. }
  214. }
  215. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  216. private static extern int current_lcid ();
  217. /* If the current_lcid() isn't known by CultureInfo,
  218. * it will throw an exception which may cause
  219. * String.Concat to try and recursively look up the
  220. * CurrentCulture, which will throw an exception, etc.
  221. * Use a boolean to short-circuit this scenario.
  222. */
  223. private static bool in_currentculture=false;
  224. public CultureInfo CurrentCulture {
  225. get {
  226. if (current_culture == null) {
  227. lock (typeof (Thread)) {
  228. if(current_culture==null) {
  229. if(in_currentculture==true) {
  230. /* Bail out */
  231. current_culture = CultureInfo.InvariantCulture;
  232. } else {
  233. in_currentculture=true;
  234. current_culture = CultureInfo.ConstructCurrentCulture ();
  235. }
  236. }
  237. in_currentculture=false;
  238. }
  239. }
  240. return(current_culture);
  241. }
  242. set {
  243. current_culture = value;
  244. }
  245. }
  246. public CultureInfo CurrentUICulture {
  247. get {
  248. if (current_ui_culture == null) {
  249. lock (this) {
  250. if(current_ui_culture==null) {
  251. /* We don't
  252. * distinguish
  253. * between
  254. * System and
  255. * UI cultures
  256. */
  257. current_ui_culture = CultureInfo.ConstructCurrentUICulture ();
  258. }
  259. }
  260. }
  261. return(current_ui_culture);
  262. }
  263. set {
  264. current_ui_culture = value;
  265. }
  266. }
  267. public bool IsThreadPoolThread {
  268. get {
  269. return IsThreadPoolThreadInternal;
  270. }
  271. }
  272. internal bool IsThreadPoolThreadInternal {
  273. get {
  274. return threadpool_thread;
  275. }
  276. set {
  277. threadpool_thread = value;
  278. }
  279. }
  280. public bool IsAlive {
  281. get {
  282. ThreadState curstate=state;
  283. if((curstate & ThreadState.Aborted) != 0 ||
  284. (curstate & ThreadState.Stopped) != 0 ||
  285. (curstate & ThreadState.Unstarted) != 0) {
  286. return(false);
  287. } else {
  288. return(true);
  289. }
  290. }
  291. }
  292. public bool IsBackground {
  293. get {
  294. if((state & ThreadState.Background) != 0) {
  295. return(true);
  296. } else {
  297. return(false);
  298. }
  299. }
  300. set {
  301. if(value==true) {
  302. set_state(ThreadState.Background);
  303. } else {
  304. clr_state(ThreadState.Background);
  305. }
  306. }
  307. }
  308. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  309. private extern string GetName_internal ();
  310. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  311. private extern void SetName_internal (String name);
  312. /*
  313. * The thread name must be shared by appdomains, so it is stored in
  314. * unmanaged code.
  315. */
  316. public string Name {
  317. get {
  318. return GetName_internal ();
  319. }
  320. set {
  321. lock (this) {
  322. if(Name!=null) {
  323. throw new InvalidOperationException ("Thread.Name can only be set once.");
  324. }
  325. SetName_internal (value);
  326. }
  327. }
  328. }
  329. [MonoTODO]
  330. public ThreadPriority Priority {
  331. get {
  332. // FIXME
  333. return(ThreadPriority.Lowest);
  334. }
  335. set {
  336. }
  337. }
  338. public ThreadState ThreadState {
  339. get {
  340. return(state);
  341. }
  342. }
  343. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  344. private extern void Abort_internal (object stateInfo);
  345. public void Abort() {
  346. Abort_internal (null);
  347. }
  348. public void Abort(object stateInfo) {
  349. Abort_internal(stateInfo);
  350. }
  351. [MonoTODO]
  352. public void Interrupt() {
  353. // FIXME
  354. }
  355. // The current thread joins with 'this'. Set ms to 0 to block
  356. // until this actually exits.
  357. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  358. private extern bool Join_internal(int ms, IntPtr handle);
  359. public void Join() {
  360. if((state & ThreadState.Unstarted) != 0) {
  361. throw new ThreadStateException("Thread has not been started");
  362. }
  363. Thread thread=CurrentThread;
  364. thread.set_state(ThreadState.WaitSleepJoin);
  365. Join_internal(Timeout.Infinite, system_thread_handle);
  366. thread.clr_state(ThreadState.WaitSleepJoin);
  367. }
  368. public bool Join(int millisecondsTimeout) {
  369. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  370. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  371. if((state & ThreadState.Unstarted) != 0) {
  372. throw new ThreadStateException("Thread has not been started");
  373. }
  374. Thread thread=CurrentThread;
  375. thread.set_state(ThreadState.WaitSleepJoin);
  376. bool ret=Join_internal(millisecondsTimeout,
  377. system_thread_handle);
  378. thread.clr_state(ThreadState.WaitSleepJoin);
  379. return(ret);
  380. }
  381. public bool Join(TimeSpan timeout) {
  382. // LAMESPEC: says to throw ArgumentException too
  383. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  384. if(ms < 0 || ms > Int32.MaxValue) {
  385. throw new ArgumentOutOfRangeException("timeout out of range");
  386. }
  387. if((state & ThreadState.Unstarted) != 0) {
  388. throw new ThreadStateException("Thread has not been started");
  389. }
  390. Thread thread=CurrentThread;
  391. thread.set_state(ThreadState.WaitSleepJoin);
  392. bool ret=Join_internal(ms, system_thread_handle);
  393. thread.clr_state(ThreadState.WaitSleepJoin);
  394. return(ret);
  395. }
  396. #if NET_1_1
  397. [MonoTODO ("seems required for multi-processors systems like Itanium")]
  398. public static void MemoryBarrier ()
  399. {
  400. throw new NotImplementedException ();
  401. }
  402. #endif
  403. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  404. private extern void Resume_internal();
  405. public void Resume ()
  406. {
  407. if ((state & ThreadState.Unstarted) != 0 || !IsAlive ||
  408. ((state & ThreadState.Suspended) == 0 && (state & ThreadState.SuspendRequested) == 0))
  409. {
  410. throw new ThreadStateException("Thread has not been started, or is dead");
  411. }
  412. Resume_internal ();
  413. }
  414. [MonoTODO]
  415. public static void SpinWait (int iterations)
  416. {
  417. throw new NotImplementedException ();
  418. }
  419. // Launches the thread
  420. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  421. private extern void Start_internal(IntPtr handle);
  422. public void Start() {
  423. lock(this) {
  424. if((state & ThreadState.Unstarted) == 0) {
  425. throw new ThreadStateException("Thread has already been started");
  426. }
  427. // Thread_internal creates the new thread, but
  428. // blocks it until Start() is called later.
  429. system_thread_handle=Thread_internal(threadstart);
  430. if (system_thread_handle == (IntPtr) 0) {
  431. throw new SystemException ("Thread creation failed");
  432. }
  433. // Launch this thread
  434. Start_internal(system_thread_handle);
  435. // Mark the thread state as Running
  436. // (which is all bits
  437. // cleared). Therefore just remove the
  438. // Unstarted bit
  439. clr_state(ThreadState.Unstarted);
  440. }
  441. }
  442. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  443. private extern void Suspend_internal();
  444. public void Suspend() {
  445. if((state & ThreadState.Unstarted) != 0 || !IsAlive) {
  446. throw new ThreadStateException("Thread has not been started, or is dead");
  447. }
  448. Suspend_internal ();
  449. }
  450. // Closes the system thread handle
  451. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  452. private extern void Thread_free_internal(IntPtr handle);
  453. ~Thread() {
  454. // Free up the handle
  455. if (system_thread_handle != (IntPtr) 0)
  456. Thread_free_internal(system_thread_handle);
  457. }
  458. private void set_state(ThreadState set) {
  459. lock(this) {
  460. state |= set;
  461. }
  462. }
  463. private void clr_state(ThreadState clr) {
  464. lock(this) {
  465. state &= ~clr;
  466. }
  467. }
  468. #if NET_1_1
  469. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  470. extern public static byte VolatileRead (ref byte address);
  471. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  472. extern public static double VolatileRead (ref double address);
  473. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  474. extern public static short VolatileRead (ref short address);
  475. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  476. extern public static int VolatileRead (ref int address);
  477. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  478. extern public static long VolatileRead (ref long address);
  479. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  480. extern public static IntPtr VolatileRead (ref IntPtr address);
  481. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  482. extern public static object VolatileRead (ref object address);
  483. [CLSCompliant(false)]
  484. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  485. extern public static sbyte VolatileRead (ref sbyte address);
  486. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  487. extern public static float VolatileRead (ref float address);
  488. [CLSCompliant (false)]
  489. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  490. extern public static ushort VolatileRead (ref ushort address);
  491. [CLSCompliant (false)]
  492. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  493. extern public static uint VolatileRead (ref uint address);
  494. [CLSCompliant (false)]
  495. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  496. extern public static ulong VolatileRead (ref ulong address);
  497. [CLSCompliant (false)]
  498. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  499. extern public static byte VolatileRead (ref UIntPtr address);
  500. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  501. extern public static void VolatileWrite (ref byte address, byte value);
  502. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  503. extern public static void VolatileWrite (ref double address, double value);
  504. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  505. extern public static void VolatileWrite (ref short address, short value);
  506. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  507. extern public static void VolatileWrite (ref int address, int value);
  508. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  509. extern public static void VolatileWrite (ref long address, long value);
  510. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  511. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  512. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  513. extern public static void VolatileWrite (ref object address, object value);
  514. [CLSCompliant(false)]
  515. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  516. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  517. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  518. extern public static void VolatileWrite (ref float address, float value);
  519. [CLSCompliant (false)]
  520. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  521. extern public static void VolatileWrite (ref ushort address, ushort value);
  522. [CLSCompliant (false)]
  523. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  524. extern public static void VolatileWrite (ref uint address, uint value);
  525. [CLSCompliant (false)]
  526. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  527. extern public static void VolatileWrite (ref ulong address, ulong value);
  528. [CLSCompliant (false)]
  529. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  530. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  531. #endif
  532. }
  533. }