|
1 | 1 |
|
2 | 2 | using System;
|
| 3 | +using System.Diagnostics; |
3 | 4 | using System.Threading;
|
4 | 5 | using System.Threading.Tasks;
|
5 | 6 |
|
@@ -30,34 +31,35 @@ public void Dispose()
|
30 | 31 | [Test]
|
31 | 32 | public void InterruptTest()
|
32 | 33 | {
|
33 |
| - int runSimpleStringReturnValue = int.MinValue; |
34 |
| - ulong pythonThreadID = ulong.MinValue; |
35 |
| - Task.Factory.StartNew(() => |
| 34 | + long pythonThreadID = 0; |
| 35 | + var asyncCall = Task.Factory.StartNew(() => |
36 | 36 | {
|
37 | 37 | using (Py.GIL())
|
38 | 38 | {
|
39 |
| - pythonThreadID = PythonEngine.GetPythonThreadID(); |
40 |
| - runSimpleStringReturnValue = PythonEngine.RunSimpleString(@" |
| 39 | + Interlocked.Exchange(ref pythonThreadID, (long)PythonEngine.GetPythonThreadID()); |
| 40 | + return PythonEngine.RunSimpleString(@" |
41 | 41 | import time
|
42 | 42 |
|
43 | 43 | while True:
|
44 | 44 | time.sleep(0.2)");
|
45 | 45 | }
|
46 | 46 | });
|
47 | 47 |
|
48 |
| - Thread.Sleep(200); |
49 |
| - |
50 |
| - Assert.AreNotEqual(ulong.MinValue, pythonThreadID); |
| 48 | + var timeout = Stopwatch.StartNew(); |
| 49 | + while (Interlocked.Read(ref pythonThreadID) == 0) |
| 50 | + { |
| 51 | + Assert.Less(timeout.Elapsed, TimeSpan.FromSeconds(5), "thread ID was not assigned in time"); |
| 52 | + } |
51 | 53 |
|
52 | 54 | using (Py.GIL())
|
53 | 55 | {
|
54 |
| - int interruptReturnValue = PythonEngine.Interrupt(pythonThreadID); |
| 56 | + int interruptReturnValue = PythonEngine.Interrupt((ulong)Interlocked.Read(ref pythonThreadID)); |
55 | 57 | Assert.AreEqual(1, interruptReturnValue);
|
56 | 58 | }
|
57 | 59 |
|
58 |
| - Thread.Sleep(300); |
| 60 | + Assert.IsTrue(asyncCall.Wait(TimeSpan.FromSeconds(5)), "Async thread was not interrupted in time"); |
59 | 61 |
|
60 |
| - Assert.AreEqual(-1, runSimpleStringReturnValue); |
| 62 | + Assert.AreEqual(-1, asyncCall.Result); |
61 | 63 | }
|
62 | 64 | }
|
63 | 65 | }
|
0 commit comments