Thread.cs 17 KB

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