forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_thread.cs
More file actions
467 lines (380 loc) · 18.2 KB
/
_thread.cs
File metadata and controls
467 lines (380 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using SpecialName = System.Runtime.CompilerServices.SpecialNameAttribute;
[assembly: PythonModule("_thread", typeof(IronPython.Modules.PythonThread))]
namespace IronPython.Modules {
public static class PythonThread {
public const string __doc__ = "Provides low level primitives for threading.";
private static readonly object _stackSizeKey = new object();
private static object _threadCountKey = new object();
[ThreadStatic] private static List<@lock>? _sentinelLocks;
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.SetModuleState(_stackSizeKey, 0);
context.EnsureModuleException("threaderror", dict, "error", "thread");
}
#region Public API Surface
public static double TIMEOUT_MAX = Math.Floor(TimeSpan.MaxValue.TotalSeconds);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly PythonType LockType = DynamicHelpers.GetPythonTypeFromType(typeof(@lock));
[Documentation("start_new_thread(function, args, [kwDict]) -> thread id\nCreates a new thread running the given function")]
public static object start_new_thread(CodeContext/*!*/ context, object? function, object? args, object? kwDict) {
if (args is not PythonTuple tupArgs) throw PythonOps.TypeError("2nd arg must be a tuple");
if (kwDict is not PythonDictionary dict) throw PythonOps.TypeError("optional 3rd arg must be a dictionary");
Thread t = CreateThread(context, new ThreadObj(context, function, tupArgs, dict).Start);
t.Start();
return t.ManagedThreadId;
}
[Documentation("start_new_thread(function, args, [kwDict]) -> thread id\nCreates a new thread running the given function")]
public static object start_new_thread(CodeContext/*!*/ context, object? function, object? args) {
if (args is not PythonTuple tupArgs) throw PythonOps.TypeError("2nd arg must be a tuple");
Thread t = CreateThread(context, new ThreadObj(context, function, tupArgs, null).Start);
t.IsBackground = true;
t.Start();
return t.ManagedThreadId;
}
/// <summary>
/// Stops execution of Python or other .NET code on the main thread. If the thread is
/// blocked in native code the thread will be interrupted after it returns back to Python
/// or other .NET code.
/// </summary>
public static void interrupt_main(CodeContext context) {
var thread = context.LanguageContext.MainThread;
if (thread != null) {
#pragma warning disable SYSLIB0006 // Thread.Abort is not supported and throws PlatformNotSupportedException on .NET Core.
thread.Abort(new KeyboardInterruptException(""));
#pragma warning restore SYSLIB0006
} else {
throw PythonOps.SystemError("no main thread has been registered");
}
}
public static void exit() {
PythonOps.SystemExit();
}
[Documentation("allocate_lock() -> lock object\nAllocates a new lock object that can be used for synchronization")]
public static object allocate_lock() {
return new @lock();
}
public static object get_ident() {
return Environment.CurrentManagedThreadId;
}
public static int stack_size(CodeContext/*!*/ context) {
return GetStackSize(context);
}
public static int stack_size(CodeContext/*!*/ context, int size) {
if (size < 32 * 1024 && size != 0) {
throw PythonOps.ValueError("size too small: {0}", size);
}
int oldSize = GetStackSize(context);
SetStackSize(context, size);
return oldSize;
}
// deprecated synonyms, wrappers over preferred names...
[Documentation("start_new(function, args, [kwDict]) -> thread id\nCreates a new thread running the given function")]
public static object start_new(CodeContext context, object? function, object? args, object? kwDict) {
return start_new_thread(context, function, args, kwDict);
}
[Documentation("start_new(function, args, [kwDict]) -> thread id\nCreates a new thread running the given function")]
public static object start_new(CodeContext context, object? function, object? args) {
return start_new_thread(context, function, args);
}
public static void exit_thread() {
exit();
}
public static object allocate() {
return allocate_lock();
}
public static int _count(CodeContext context) {
return (int)context.LanguageContext.GetOrCreateModuleState<object>(_threadCountKey, () => 0);
}
[Documentation("_set_sentinel() -> lock\n\nSet a sentinel lock that will be released when the current thread\nstate is finalized (after it is untied from the interpreter).\n\nThis is a private API for the threading module.")]
public static object _set_sentinel(CodeContext context) {
if (_sentinelLocks == null) {
_sentinelLocks = new List<@lock>();
}
var obj = new @lock();
_sentinelLocks.Add(obj);
return obj;
}
#endregion
[PythonType, PythonHidden]
public sealed class @lock {
private AutoResetEvent? blockEvent;
private Thread? curHolder;
public object __enter__() {
acquire();
return this;
}
public void __exit__(CodeContext/*!*/ context, [NotNone] params object[] args) {
release(context);
}
public bool acquire(bool blocking = true, double timeout = -1) {
var timespan = Timeout.InfiniteTimeSpan;
if (timeout != -1) {
if (!blocking) throw PythonOps.ValueError("can't specify a timeout for a non-blocking call");
if (timeout < 0) throw PythonOps.ValueError("timeout value must be a non-negative number");
timespan = TimeSpan.FromSeconds(timeout);
}
for (; ; ) {
if (Interlocked.CompareExchange(ref curHolder, Thread.CurrentThread, null) is null) {
return true;
}
if (!blocking) {
return false;
}
if (blockEvent == null) {
// try again in case someone released us, checked the block
// event and discovered it was null so they didn't set it.
CreateBlockEvent();
continue;
}
if (!blockEvent.WaitOne(timespan)) {
return false;
}
GC.KeepAlive(this);
}
}
public void release(CodeContext/*!*/ context) {
if (Interlocked.Exchange(ref curHolder, null) is null) {
throw PythonOps.RuntimeError("release unlocked lock");
}
if (blockEvent != null) {
// if this isn't set yet we race, it's handled in Acquire()
blockEvent.Set();
GC.KeepAlive(this);
}
}
public bool locked()
=> curHolder is not null;
public string __repr__() {
if (curHolder is null) {
return $"<unlocked _thread.lock object at 0x{IdDispenser.GetId(this):X16}>";
}
return $"<locked _thread.lock object at 0x{IdDispenser.GetId(this):X16}>";
}
private void CreateBlockEvent() {
AutoResetEvent are = new AutoResetEvent(false);
if (Interlocked.CompareExchange(ref blockEvent, are, null) is not null) {
are.Close();
}
}
}
[PythonType]
public sealed class RLock {
private AutoResetEvent? blockEvent;
private Thread? curHolder;
private int count;
public object __enter__() {
acquire();
return this;
}
public void __exit__(CodeContext/*!*/ context, [NotNone] params object[] args) {
release();
}
public bool acquire(bool blocking = true, double timeout = -1) {
var timespan = Timeout.InfiniteTimeSpan;
if (timeout != -1) {
if (!blocking) throw PythonOps.ValueError("can't specify a timeout for a non-blocking call");
if (timeout < 0) throw PythonOps.ValueError("timeout value must be a non-negative number");
timespan = TimeSpan.FromSeconds(timeout);
}
var currentThread = Thread.CurrentThread;
for (; ; ) {
var previousThread = Interlocked.CompareExchange(ref curHolder, currentThread, null);
if (previousThread == currentThread) {
count++;
return true;
}
if (previousThread is null) {
count = 1;
return true;
}
if (!blocking) {
return false;
}
if (blockEvent is null) {
// try again in case someone released us, checked the block
// event and discovered it was null so they didn't set it.
CreateBlockEvent();
continue;
}
if (!blockEvent.WaitOne(timespan)) {
return false;
}
GC.KeepAlive(this);
}
}
public void release() {
var currentThread = Thread.CurrentThread;
if (curHolder != currentThread) {
throw PythonOps.RuntimeError("cannot release un-acquired lock");
}
if (--count > 0) {
return;
}
if (Interlocked.Exchange(ref curHolder, null) is null) {
throw PythonOps.RuntimeError("release unlocked lock");
}
if (blockEvent is not null) {
// if this isn't set yet we race, it's handled in acquire()
blockEvent.Set();
GC.KeepAlive(this);
}
}
public string __repr__() {
if (curHolder is null) {
return $"<unlocked _thread.RLock object owner=0 count=0 at 0x{IdDispenser.GetId(this):X16}>";
}
return $"<locked _thread.RLock object owner={curHolder?.ManagedThreadId} count={count} at 0x{IdDispenser.GetId(this):X16}>";
}
public void _acquire_restore([NotNone] PythonTuple state) {
acquire();
count = (int)state[0]!;
curHolder = (Thread?)state[1];
}
public PythonTuple _release_save() {
var count = Interlocked.Exchange(ref this.count, 0);
if (count == 0) {
throw PythonOps.RuntimeError("cannot release un-acquired lock");
}
// release
var owner = Interlocked.Exchange(ref curHolder, null);
blockEvent?.Set();
return PythonTuple.MakeTuple(count, owner);
}
public bool _is_owned()
=> curHolder == Thread.CurrentThread;
private void CreateBlockEvent() {
AutoResetEvent are = new AutoResetEvent(false);
if (Interlocked.CompareExchange(ref blockEvent, are, null) != null) {
are.Close();
}
}
}
#region Internal Implementation details
private static Thread CreateThread(CodeContext/*!*/ context, ThreadStart start) {
int size = GetStackSize(context);
return (size != 0) ? new Thread(start, size) : new Thread(start);
}
private class ThreadObj {
private readonly object? _func;
private readonly PythonDictionary? _kwargs;
private readonly PythonTuple _args;
private readonly CodeContext _context;
public ThreadObj(CodeContext context, object? function, PythonTuple args, PythonDictionary? kwargs) {
_func = function;
_kwargs = kwargs;
_args = args;
_context = context;
}
public void Start() {
lock (_threadCountKey) {
int startCount = (int)_context.LanguageContext.GetOrCreateModuleState<object>(_threadCountKey, () => 0);
_context.LanguageContext.SetModuleState(_threadCountKey, startCount + 1);
}
try {
if (_kwargs != null) {
PythonCalls.CallWithKeywordArgs(_context, _func, _args.ToArray(), new PythonDictionary(_kwargs));
} else {
PythonCalls.Call(_context, _func, _args.ToArray());
}
} catch (SystemExitException) {
// ignore and quit
} catch (Exception e) {
PythonOps.PrintWithDest(_context, _context.LanguageContext.SystemStandardError, "Unhandled exception on thread");
string result = _context.LanguageContext.FormatException(e);
PythonOps.PrintWithDest(_context, _context.LanguageContext.SystemStandardError, result);
} finally {
lock (_threadCountKey) {
int curCount = (int)_context.LanguageContext.GetModuleState(_threadCountKey);
_context.LanguageContext.SetModuleState(_threadCountKey, curCount - 1);
}
// release sentinel locks if locked.
if (_sentinelLocks != null) {
foreach (var obj in _sentinelLocks) {
if (obj.locked()) {
obj.release(_context);
}
}
_sentinelLocks.Clear();
}
}
}
}
#endregion
private static int GetStackSize(CodeContext/*!*/ context) {
return (int)context.LanguageContext.GetModuleState(_stackSizeKey);
}
private static void SetStackSize(CodeContext/*!*/ context, int stackSize) {
context.LanguageContext.SetModuleState(_stackSizeKey, stackSize);
}
[PythonType]
public class _local {
private readonly PythonDictionary/*!*/ _dict = new PythonDictionary(new ThreadLocalDictionaryStorage());
#region Custom Attribute Access
[SpecialName]
public object GetCustomMember([NotNone] string name) {
return _dict.get(name, OperationFailed.Value);
}
[SpecialName]
public void SetMemberAfter([NotNone] string name, object? value) {
_dict[name] = value;
}
[SpecialName]
public void DeleteMember([NotNone] string name) {
_dict.__delitem__(name);
}
#endregion
public PythonDictionary/*!*/ __dict__ {
get {
return _dict;
}
}
#region Dictionary Storage
/// <summary>
/// Provides a dictionary storage implementation whose storage is local to
/// the thread.
/// </summary>
private class ThreadLocalDictionaryStorage : DictionaryStorage {
private readonly Microsoft.Scripting.Utils.ThreadLocal<CommonDictionaryStorage> _storage = new Microsoft.Scripting.Utils.ThreadLocal<CommonDictionaryStorage>();
public override void Add(ref DictionaryStorage storage, object? key, object? value) {
GetStorage().Add(key, value);
}
public override bool Contains(object? key) {
return GetStorage().Contains(key);
}
public override bool Remove(ref DictionaryStorage storage, object? key) {
return GetStorage().Remove(ref storage, key);
}
public override DictionaryStorage AsMutable(ref DictionaryStorage storage) => this;
public override bool TryGetValue(object? key, out object? value) {
return GetStorage().TryGetValue(key, out value);
}
public override int Count {
get { return GetStorage().Count; }
}
public override void Clear(ref DictionaryStorage storage) {
GetStorage().Clear(ref storage);
}
public override List<KeyValuePair<object?, object?>>/*!*/ GetItems() {
return GetStorage().GetItems();
}
private CommonDictionaryStorage/*!*/ GetStorage() {
return _storage.GetOrCreate(() => new CommonDictionaryStorage());
}
}
#endregion
}
}
}