Thread.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. //
  2. // System.Threading.Thread.cs
  3. //
  4. // Author:
  5. // Dick Porter ([email protected])
  6. //
  7. // (C) Ximian, Inc. http://www.ximian.com
  8. //
  9. using System.Runtime.Remoting.Contexts;
  10. using System.Security.Permissions;
  11. using System.Security.Principal;
  12. using System.Globalization;
  13. using System.Runtime.CompilerServices;
  14. using System.Collections;
  15. namespace System.Threading
  16. {
  17. public sealed class Thread
  18. {
  19. #region Sync with object.h
  20. // stores a thread handle
  21. private IntPtr system_thread_handle;
  22. private CultureInfo current_culture;
  23. private CultureInfo current_ui_culture;
  24. private bool threadpool_thread;
  25. /* accessed only from unmanaged code */
  26. private IntPtr name;
  27. private int name_len;
  28. private ThreadState state = ThreadState.Unstarted;
  29. private object abort_exc;
  30. internal object abort_state;
  31. /* thread_id is only accessed from unmanaged code */
  32. private int thread_id;
  33. /* start_notify is used by the runtime to signal that Start()
  34. * is ok to return
  35. */
  36. private IntPtr start_notify;
  37. private IntPtr stack_ptr;
  38. private IntPtr static_data;
  39. private IntPtr jit_data;
  40. private IntPtr lock_data;
  41. private IntPtr appdomain_refs;
  42. #endregion
  43. private ThreadStart threadstart;
  44. private string thread_name=null;
  45. private IPrincipal _principal;
  46. public static Context CurrentContext {
  47. get {
  48. return(AppDomain.InternalGetContext ());
  49. }
  50. }
  51. public static IPrincipal CurrentPrincipal {
  52. get {
  53. IPrincipal p = null;
  54. lock (typeof (Thread)) {
  55. p = CurrentThread._principal;
  56. if (p == null)
  57. p = GetDomain ().DefaultPrincipal;
  58. }
  59. return p;
  60. }
  61. set {
  62. new SecurityPermission (SecurityPermissionFlag.ControlPrincipal).Demand ();
  63. CurrentThread._principal = value;
  64. }
  65. }
  66. // Looks up the object associated with the current thread
  67. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  68. private extern static Thread CurrentThread_internal();
  69. public static Thread CurrentThread {
  70. get {
  71. return(CurrentThread_internal());
  72. }
  73. }
  74. internal static int CurrentThreadId {
  75. get {
  76. return CurrentThread.thread_id;
  77. }
  78. }
  79. // Looks up the slot hash for the current thread
  80. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  81. private extern static Hashtable SlotHash_lookup();
  82. // Stores the slot hash for the current thread
  83. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  84. private extern static void SlotHash_store(Hashtable slothash);
  85. private static Hashtable GetTLSSlotHash() {
  86. Hashtable slothash=SlotHash_lookup();
  87. if(slothash==null) {
  88. // Not synchronised, because this is
  89. // thread specific anyway.
  90. slothash=new Hashtable();
  91. SlotHash_store(slothash);
  92. }
  93. return(slothash);
  94. }
  95. internal static object ResetDataStoreStatus () {
  96. Hashtable slothash=SlotHash_lookup();
  97. SlotHash_store(null);
  98. return slothash;
  99. }
  100. internal static void RestoreDataStoreStatus (object data) {
  101. SlotHash_store((Hashtable)data);
  102. }
  103. public static LocalDataStoreSlot AllocateDataSlot() {
  104. LocalDataStoreSlot slot = new LocalDataStoreSlot();
  105. return(slot);
  106. }
  107. // Stores a hash keyed by strings of LocalDataStoreSlot objects
  108. static Hashtable datastorehash;
  109. private static void InitDataStoreHash () {
  110. lock (typeof (Thread)) {
  111. if (datastorehash == null) {
  112. datastorehash = Hashtable.Synchronized(new Hashtable());
  113. }
  114. }
  115. }
  116. public static LocalDataStoreSlot AllocateNamedDataSlot(string name) {
  117. lock (typeof (Thread)) {
  118. if (datastorehash == null)
  119. InitDataStoreHash ();
  120. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash[name];
  121. if(slot!=null) {
  122. // This exception isnt documented (of
  123. // course) but .net throws it
  124. throw new ArgumentException("Named data slot already added");
  125. }
  126. slot = new LocalDataStoreSlot();
  127. datastorehash.Add(name, slot);
  128. return(slot);
  129. }
  130. }
  131. public static void FreeNamedDataSlot(string name) {
  132. lock (typeof (Thread)) {
  133. if (datastorehash == null)
  134. InitDataStoreHash ();
  135. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  136. if(slot!=null) {
  137. datastorehash.Remove(slot);
  138. }
  139. }
  140. }
  141. public static object GetData(LocalDataStoreSlot slot) {
  142. Hashtable slothash=GetTLSSlotHash();
  143. return(slothash[slot]);
  144. }
  145. public static AppDomain GetDomain() {
  146. return AppDomain.CurrentDomain;
  147. }
  148. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  149. public extern static int GetDomainID();
  150. public static LocalDataStoreSlot GetNamedDataSlot(string name) {
  151. if (datastorehash == null)
  152. InitDataStoreHash ();
  153. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  154. if(slot==null) {
  155. slot=AllocateNamedDataSlot(name);
  156. }
  157. return(slot);
  158. }
  159. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  160. private extern static void ResetAbort_internal();
  161. public static void ResetAbort()
  162. {
  163. Thread thread=CurrentThread;
  164. thread.clr_state(ThreadState.AbortRequested);
  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. set_state(ThreadState.AbortRequested);
  347. Abort_internal (null);
  348. }
  349. public void Abort(object stateInfo) {
  350. set_state(ThreadState.AbortRequested);
  351. Abort_internal(stateInfo);
  352. }
  353. [MonoTODO]
  354. public void Interrupt() {
  355. // FIXME
  356. }
  357. // The current thread joins with 'this'. Set ms to 0 to block
  358. // until this actually exits.
  359. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  360. private extern bool Join_internal(int ms, IntPtr handle);
  361. public void Join() {
  362. if((state & ThreadState.Unstarted) != 0) {
  363. throw new ThreadStateException("Thread has not been started");
  364. }
  365. Thread thread=CurrentThread;
  366. thread.set_state(ThreadState.WaitSleepJoin);
  367. Join_internal(Timeout.Infinite, system_thread_handle);
  368. thread.clr_state(ThreadState.WaitSleepJoin);
  369. }
  370. public bool Join(int millisecondsTimeout) {
  371. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  372. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  373. if((state & ThreadState.Unstarted) != 0) {
  374. throw new ThreadStateException("Thread has not been started");
  375. }
  376. Thread thread=CurrentThread;
  377. thread.set_state(ThreadState.WaitSleepJoin);
  378. bool ret=Join_internal(millisecondsTimeout,
  379. system_thread_handle);
  380. thread.clr_state(ThreadState.WaitSleepJoin);
  381. return(ret);
  382. }
  383. public bool Join(TimeSpan timeout) {
  384. // LAMESPEC: says to throw ArgumentException too
  385. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  386. if(ms < 0 || ms > Int32.MaxValue) {
  387. throw new ArgumentOutOfRangeException("timeout out of range");
  388. }
  389. if((state & ThreadState.Unstarted) != 0) {
  390. throw new ThreadStateException("Thread has not been started");
  391. }
  392. Thread thread=CurrentThread;
  393. thread.set_state(ThreadState.WaitSleepJoin);
  394. bool ret=Join_internal(ms, system_thread_handle);
  395. thread.clr_state(ThreadState.WaitSleepJoin);
  396. return(ret);
  397. }
  398. [MonoTODO]
  399. public void Resume() {
  400. throw new NotImplementedException ();
  401. }
  402. // Launches the thread
  403. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  404. private extern void Start_internal(IntPtr handle);
  405. public void Start() {
  406. lock(this) {
  407. if((state & ThreadState.Unstarted) == 0) {
  408. throw new ThreadStateException("Thread has already been started");
  409. }
  410. // Thread_internal creates the new thread, but
  411. // blocks it until Start() is called later.
  412. system_thread_handle=Thread_internal(threadstart);
  413. if (system_thread_handle == (IntPtr) 0) {
  414. throw new SystemException ("Thread creation failed");
  415. }
  416. // Launch this thread
  417. Start_internal(system_thread_handle);
  418. // Mark the thread state as Running
  419. // (which is all bits
  420. // cleared). Therefore just remove the
  421. // Unstarted bit
  422. clr_state(ThreadState.Unstarted);
  423. }
  424. }
  425. [MonoTODO]
  426. public void Suspend() {
  427. if((state & ThreadState.Unstarted) != 0 || !IsAlive) {
  428. throw new ThreadStateException("Thread has not been started, or is dead");
  429. }
  430. set_state(ThreadState.SuspendRequested);
  431. // FIXME - somehow let the interpreter know that
  432. // this thread should now suspend
  433. Console.WriteLine ("WARNING: Thread.Suspend () partially implemented");
  434. }
  435. // Closes the system thread handle
  436. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  437. private extern void Thread_free_internal(IntPtr handle);
  438. ~Thread() {
  439. // Free up the handle
  440. Thread_free_internal(system_thread_handle);
  441. }
  442. private void set_state(ThreadState set) {
  443. lock(this) {
  444. state |= set;
  445. }
  446. }
  447. private void clr_state(ThreadState clr) {
  448. lock(this) {
  449. state &= ~clr;
  450. }
  451. }
  452. #if NET_1_1
  453. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  454. extern public static byte VolatileRead (ref byte address);
  455. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  456. extern public static double VolatileRead (ref double address);
  457. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  458. extern public static short VolatileRead (ref short address);
  459. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  460. extern public static int VolatileRead (ref int address);
  461. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  462. extern public static long VolatileRead (ref long address);
  463. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  464. extern public static IntPtr VolatileRead (ref IntPtr address);
  465. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  466. extern public static object VolatileRead (ref object address);
  467. [CLSCompliant(false)]
  468. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  469. extern public static sbyte VolatileRead (ref sbyte address);
  470. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  471. extern public static float VolatileRead (ref float address);
  472. [CLSCompliant (false)]
  473. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  474. extern public static ushort VolatileRead (ref ushort address);
  475. [CLSCompliant (false)]
  476. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  477. extern public static uint VolatileRead (ref uint address);
  478. [CLSCompliant (false)]
  479. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  480. extern public static ulong VolatileRead (ref ulong address);
  481. [CLSCompliant (false)]
  482. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  483. extern public static byte VolatileRead (ref UIntPtr address);
  484. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  485. extern public static void VolatileWrite (ref byte address, byte value);
  486. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  487. extern public static void VolatileWrite (ref double address, double value);
  488. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  489. extern public static void VolatileWrite (ref short address, short value);
  490. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  491. extern public static void VolatileWrite (ref int address, int value);
  492. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  493. extern public static void VolatileWrite (ref long address, long value);
  494. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  495. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  496. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  497. extern public static void VolatileWrite (ref object address, object value);
  498. [CLSCompliant(false)]
  499. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  500. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  501. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  502. extern public static void VolatileWrite (ref float address, float value);
  503. [CLSCompliant (false)]
  504. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  505. extern public static void VolatileWrite (ref ushort address, ushort value);
  506. [CLSCompliant (false)]
  507. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  508. extern public static void VolatileWrite (ref uint address, uint value);
  509. [CLSCompliant (false)]
  510. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  511. extern public static void VolatileWrite (ref ulong address, ulong value);
  512. [CLSCompliant (false)]
  513. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  514. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  515. #endif
  516. }
  517. }