Merge pull request #1781 from alexrp/master
[mono.git] / mcs / class / corlib / System.Threading / ThreadLocal.cs
1 // 
2 // ThreadLocal.cs
3 //  
4 // Author:
5 //       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
6 //       Rewritten by Paolo Molaro (lupus@ximian.com)
7 // 
8 // Copyright (c) 2009 Jérémie "Garuma" Laval
9 // 
10 // Permission is hereby granted, free of charge, to any person obtaining a copy
11 // of this software and associated documentation files (the "Software"), to deal
12 // in the Software without restriction, including without limitation the rights
13 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 // copies of the Software, and to permit persons to whom the Software is
15 // furnished to do so, subject to the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be included in
18 // all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 // THE SOFTWARE.
27
28 using System;
29 using System.Collections.Generic;
30 using System.Runtime.Serialization;
31 using System.Runtime.InteropServices;
32 using System.Security.Permissions;
33
34 namespace System.Threading
35 {
36         [System.Diagnostics.DebuggerDisplay ("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}")]
37         public class ThreadLocal<T> : IDisposable
38         {
39                 struct TlsDatum {
40                         internal sbyte state; /* 0 uninitialized, < 0 initializing, > 0 inited */
41                         internal Exception cachedException; /* this is per-thread */
42                         internal T data;
43                 }
44
45                 Func<T> valueFactory;
46                 /* The tlsdata field is handled magically by the JIT
47                  * It must be a struct and it is always accessed by ldflda: the JIT, instead of
48                  * computing the address inside the instance, will return the address of the variable
49                  * for the current thread (based on tls_offset). This magic wouldn't be needed if C#
50                  * let us declare an icall with a TlsDatum& return type...
51                  * For this same reason, we must check tls_offset for != 0 to make sure it's valid before accessing tlsdata
52                  * The address of the tls var is cached per method at the first IL ldflda instruction, so care must be taken
53                  * not to cause it to be conditionally executed.
54                  */
55                 uint tls_offset;
56                 TlsDatum tlsdata;
57                 
58                 public ThreadLocal ()
59                 {
60                         tls_offset = Thread.AllocTlsData (typeof (TlsDatum));
61                 }
62
63                 public ThreadLocal (Func<T> valueFactory) : this ()
64                 {
65                         if (valueFactory == null)
66                                 throw new ArgumentNullException ("valueFactory");
67                         this.valueFactory = valueFactory;
68                 }
69
70                 public ThreadLocal (bool trackAllValues) : this () {
71                         if (trackAllValues)
72                                 throw new NotImplementedException ();
73                 }
74
75                 public ThreadLocal (Func<T> valueFactory, bool trackAllValues) : this (valueFactory) {
76                         if (trackAllValues)
77                                 throw new NotImplementedException ();
78                 }
79
80                 public void Dispose ()
81                 {
82                         Dispose (true);
83                 }
84                 
85                 protected virtual void Dispose (bool disposing)
86                 {
87                         if (tls_offset != 0) {
88                                 uint o = tls_offset;
89                                 tls_offset = 0;
90                                 if (disposing)
91                                         valueFactory = null;
92                                 Thread.DestroyTlsData (o);
93                                 GC.SuppressFinalize (this);
94                         }
95                 }
96
97                 ~ThreadLocal ()
98                 {
99                         Dispose (false);
100                 }
101                 
102                 public bool IsValueCreated {
103                         get {
104                                 if (tls_offset == 0)
105                                         throw new ObjectDisposedException ("ThreadLocal object");
106                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
107                                 return tlsdata.state > 0;
108                         }
109                 }
110
111                 T GetSlowPath () {
112                         /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
113                         if (tlsdata.cachedException != null)
114                                 throw tlsdata.cachedException;
115                         if (tlsdata.state < 0)
116                                 throw new InvalidOperationException ("The initialization function attempted to reference Value recursively");
117                         tlsdata.state = -1;
118                         if (valueFactory != null) {
119                                 try {
120                                         tlsdata.data = valueFactory ();
121                                 } catch (Exception ex) {
122                                         tlsdata.cachedException = ex;
123                                         throw ex;
124                                 }
125                         } else {
126                                 tlsdata.data = default (T);
127                         }
128                         tlsdata.state = 1;
129                         return tlsdata.data;
130                 }
131
132                 [System.Diagnostics.DebuggerBrowsableAttribute (System.Diagnostics.DebuggerBrowsableState.Never)]
133                 public T Value {
134                         get {
135                                 if (tls_offset == 0)
136                                         throw new ObjectDisposedException ("ThreadLocal object");
137                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
138                                 if (tlsdata.state > 0)
139                                         return tlsdata.data;
140                                 return GetSlowPath ();
141                         }
142                         set {
143                                 if (tls_offset == 0)
144                                         throw new ObjectDisposedException ("ThreadLocal object");
145                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
146                                 tlsdata.state = 1;
147                                 tlsdata.data = value;
148                         }
149                 }
150
151                 public IList<T> Values {
152                         get {
153                                 if (tls_offset == 0)
154                                         throw new ObjectDisposedException ("ThreadLocal object");
155                                 throw new NotImplementedException ();
156                         }
157                 }
158
159                 public override string ToString ()
160                 {
161                         return Value.ToString ();
162                 }
163                 
164         }
165 }