Thread.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. try {
  235. current_culture = new CultureInfo (current_lcid ());
  236. } catch (ArgumentException) {
  237. current_culture = CultureInfo.InvariantCulture;
  238. }
  239. }
  240. }
  241. in_currentculture=false;
  242. }
  243. }
  244. return(current_culture);
  245. }
  246. set {
  247. current_culture = value;
  248. }
  249. }
  250. public CultureInfo CurrentUICulture {
  251. get {
  252. if (current_ui_culture == null) {
  253. lock (this) {
  254. if(current_ui_culture==null) {
  255. /* We don't
  256. * distinguish
  257. * between
  258. * System and
  259. * UI cultures
  260. */
  261. try {
  262. current_ui_culture = new CultureInfo (current_lcid ());
  263. } catch (ArgumentException) {
  264. current_ui_culture = CultureInfo.InvariantCulture;
  265. }
  266. }
  267. }
  268. }
  269. return(current_ui_culture);
  270. }
  271. set {
  272. current_ui_culture = value;
  273. }
  274. }
  275. public bool IsThreadPoolThread {
  276. get {
  277. return IsThreadPoolThreadInternal;
  278. }
  279. }
  280. internal bool IsThreadPoolThreadInternal {
  281. get {
  282. return threadpool_thread;
  283. }
  284. set {
  285. threadpool_thread = value;
  286. }
  287. }
  288. public bool IsAlive {
  289. get {
  290. ThreadState curstate=state;
  291. if((curstate & ThreadState.Aborted) != 0 ||
  292. (curstate & ThreadState.Stopped) != 0 ||
  293. (curstate & ThreadState.Unstarted) != 0) {
  294. return(false);
  295. } else {
  296. return(true);
  297. }
  298. }
  299. }
  300. public bool IsBackground {
  301. get {
  302. if((state & ThreadState.Background) != 0) {
  303. return(true);
  304. } else {
  305. return(false);
  306. }
  307. }
  308. set {
  309. if(value==true) {
  310. set_state(ThreadState.Background);
  311. } else {
  312. clr_state(ThreadState.Background);
  313. }
  314. }
  315. }
  316. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  317. private extern string GetName_internal ();
  318. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  319. private extern void SetName_internal (String name);
  320. /*
  321. * The thread name must be shared by appdomains, so it is stored in
  322. * unmanaged code.
  323. */
  324. public string Name {
  325. get {
  326. return GetName_internal ();
  327. }
  328. set {
  329. lock (this) {
  330. if(Name!=null) {
  331. throw new InvalidOperationException ("Thread.Name can only be set once.");
  332. }
  333. SetName_internal (value);
  334. }
  335. }
  336. }
  337. [MonoTODO]
  338. public ThreadPriority Priority {
  339. get {
  340. // FIXME
  341. return(ThreadPriority.Lowest);
  342. }
  343. set {
  344. }
  345. }
  346. public ThreadState ThreadState {
  347. get {
  348. return(state);
  349. }
  350. }
  351. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  352. private extern void Abort_internal (object stateInfo);
  353. public void Abort() {
  354. set_state(ThreadState.AbortRequested);
  355. Abort_internal (null);
  356. }
  357. public void Abort(object stateInfo) {
  358. set_state(ThreadState.AbortRequested);
  359. Abort_internal(stateInfo);
  360. }
  361. [MonoTODO]
  362. public void Interrupt() {
  363. // FIXME
  364. }
  365. // The current thread joins with 'this'. Set ms to 0 to block
  366. // until this actually exits.
  367. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  368. private extern bool Join_internal(int ms, IntPtr handle);
  369. public void Join() {
  370. if((state & ThreadState.Unstarted) != 0) {
  371. throw new ThreadStateException("Thread has not been started");
  372. }
  373. Thread thread=CurrentThread;
  374. thread.set_state(ThreadState.WaitSleepJoin);
  375. Join_internal(Timeout.Infinite, system_thread_handle);
  376. thread.clr_state(ThreadState.WaitSleepJoin);
  377. }
  378. public bool Join(int millisecondsTimeout) {
  379. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  380. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  381. if((state & ThreadState.Unstarted) != 0) {
  382. throw new ThreadStateException("Thread has not been started");
  383. }
  384. Thread thread=CurrentThread;
  385. thread.set_state(ThreadState.WaitSleepJoin);
  386. bool ret=Join_internal(millisecondsTimeout,
  387. system_thread_handle);
  388. thread.clr_state(ThreadState.WaitSleepJoin);
  389. return(ret);
  390. }
  391. public bool Join(TimeSpan timeout) {
  392. // LAMESPEC: says to throw ArgumentException too
  393. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  394. if(ms < 0 || ms > Int32.MaxValue) {
  395. throw new ArgumentOutOfRangeException("timeout out of range");
  396. }
  397. if((state & ThreadState.Unstarted) != 0) {
  398. throw new ThreadStateException("Thread has not been started");
  399. }
  400. Thread thread=CurrentThread;
  401. thread.set_state(ThreadState.WaitSleepJoin);
  402. bool ret=Join_internal(ms, system_thread_handle);
  403. thread.clr_state(ThreadState.WaitSleepJoin);
  404. return(ret);
  405. }
  406. [MonoTODO]
  407. public void Resume() {
  408. throw new NotImplementedException ();
  409. }
  410. // Launches the thread
  411. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  412. private extern void Start_internal(IntPtr handle);
  413. public void Start() {
  414. lock(this) {
  415. if((state & ThreadState.Unstarted) == 0) {
  416. throw new ThreadStateException("Thread has already been started");
  417. }
  418. // Thread_internal creates the new thread, but
  419. // blocks it until Start() is called later.
  420. system_thread_handle=Thread_internal(threadstart);
  421. if (system_thread_handle == (IntPtr) 0) {
  422. throw new SystemException ("Thread creation failed");
  423. }
  424. // Launch this thread
  425. Start_internal(system_thread_handle);
  426. // Mark the thread state as Running
  427. // (which is all bits
  428. // cleared). Therefore just remove the
  429. // Unstarted bit
  430. clr_state(ThreadState.Unstarted);
  431. }
  432. }
  433. [MonoTODO]
  434. public void Suspend() {
  435. if((state & ThreadState.Unstarted) != 0 || !IsAlive) {
  436. throw new ThreadStateException("Thread has not been started, or is dead");
  437. }
  438. set_state(ThreadState.SuspendRequested);
  439. // FIXME - somehow let the interpreter know that
  440. // this thread should now suspend
  441. Console.WriteLine ("WARNING: Thread.Suspend () partially implemented");
  442. }
  443. // Closes the system thread handle
  444. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  445. private extern void Thread_free_internal(IntPtr handle);
  446. ~Thread() {
  447. // Free up the handle
  448. Thread_free_internal(system_thread_handle);
  449. }
  450. private void set_state(ThreadState set) {
  451. lock(this) {
  452. state |= set;
  453. }
  454. }
  455. private void clr_state(ThreadState clr) {
  456. lock(this) {
  457. state &= ~clr;
  458. }
  459. }
  460. #if NET_1_1
  461. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  462. extern public static byte VolatileRead (ref byte address);
  463. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  464. extern public static double VolatileRead (ref double address);
  465. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  466. extern public static short VolatileRead (ref short address);
  467. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  468. extern public static int VolatileRead (ref int address);
  469. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  470. extern public static long VolatileRead (ref long address);
  471. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  472. extern public static IntPtr VolatileRead (ref IntPtr address);
  473. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  474. extern public static object VolatileRead (ref object address);
  475. [CLSCompliant(false)]
  476. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  477. extern public static sbyte VolatileRead (ref sbyte address);
  478. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  479. extern public static float VolatileRead (ref float address);
  480. [CLSCompliant (false)]
  481. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  482. extern public static ushort VolatileRead (ref ushort address);
  483. [CLSCompliant (false)]
  484. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  485. extern public static uint VolatileRead (ref uint address);
  486. [CLSCompliant (false)]
  487. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  488. extern public static ulong VolatileRead (ref ulong address);
  489. [CLSCompliant (false)]
  490. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  491. extern public static byte VolatileRead (ref UIntPtr address);
  492. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  493. extern public static void VolatileWrite (ref byte address, byte value);
  494. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  495. extern public static void VolatileWrite (ref double address, double value);
  496. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  497. extern public static void VolatileWrite (ref short address, short value);
  498. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  499. extern public static void VolatileWrite (ref int address, int value);
  500. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  501. extern public static void VolatileWrite (ref long address, long value);
  502. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  503. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  504. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  505. extern public static void VolatileWrite (ref object address, object value);
  506. [CLSCompliant(false)]
  507. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  508. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  509. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  510. extern public static void VolatileWrite (ref float address, float value);
  511. [CLSCompliant (false)]
  512. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  513. extern public static void VolatileWrite (ref ushort address, ushort value);
  514. [CLSCompliant (false)]
  515. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  516. extern public static void VolatileWrite (ref uint address, uint value);
  517. [CLSCompliant (false)]
  518. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  519. extern public static void VolatileWrite (ref ulong address, ulong value);
  520. [CLSCompliant (false)]
  521. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  522. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  523. #endif
  524. }
  525. }