|
| 1 | + |
| 2 | +using System; |
| 3 | +using System.Runtime.InteropServices; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +using NUnit.Framework; |
| 8 | + |
| 9 | +using Python.Runtime; |
| 10 | + |
| 11 | +namespace Python.EmbeddingTest |
| 12 | +{ |
| 13 | + public class TestInterrupt |
| 14 | + { |
| 15 | + private IntPtr _threadState; |
| 16 | + |
| 17 | + [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] |
| 18 | + private static extern uint GetCurrentThreadId(); |
| 19 | + |
| 20 | + [DllImport("libc", EntryPoint = "pthread_self")] |
| 21 | + private static extern IntPtr pthread_selfLinux(); |
| 22 | + |
| 23 | + [DllImport("pthread", EntryPoint = "pthread_self", CallingConvention = CallingConvention.Cdecl)] |
| 24 | + private static extern ulong pthread_selfOSX(); |
| 25 | + |
| 26 | + [OneTimeSetUp] |
| 27 | + public void SetUp() |
| 28 | + { |
| 29 | + PythonEngine.Initialize(); |
| 30 | + _threadState = PythonEngine.BeginAllowThreads(); |
| 31 | + } |
| 32 | + |
| 33 | + [OneTimeTearDown] |
| 34 | + public void Dispose() |
| 35 | + { |
| 36 | + PythonEngine.EndAllowThreads(_threadState); |
| 37 | + PythonEngine.Shutdown(); |
| 38 | + } |
| 39 | + |
| 40 | + [Test] |
| 41 | + public void InterruptTest() |
| 42 | + { |
| 43 | + int runSimpleStringReturnValue = int.MinValue; |
| 44 | + ulong nativeThreadId = 0; |
| 45 | + Task.Factory.StartNew(() => |
| 46 | + { |
| 47 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 48 | + { |
| 49 | + nativeThreadId = GetCurrentThreadId(); |
| 50 | + } |
| 51 | + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) |
| 52 | + { |
| 53 | + nativeThreadId = (ulong)pthread_selfLinux(); |
| 54 | + } |
| 55 | + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| 56 | + { |
| 57 | + nativeThreadId = pthread_selfOSX(); |
| 58 | + } |
| 59 | + |
| 60 | + using (Py.GIL()) |
| 61 | + { |
| 62 | + runSimpleStringReturnValue = PythonEngine.RunSimpleString(@" |
| 63 | +import time |
| 64 | +
|
| 65 | +while True: |
| 66 | + time.sleep(0.2)"); |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + Thread.Sleep(100); |
| 71 | + |
| 72 | + using (Py.GIL()) |
| 73 | + { |
| 74 | + int interruptReturnValue = PythonEngine.Interrupt(nativeThreadId); |
| 75 | + Assert.AreEqual(1, interruptReturnValue); |
| 76 | + } |
| 77 | + |
| 78 | + Thread.Sleep(200); |
| 79 | + |
| 80 | + Assert.AreEqual(-1, runSimpleStringReturnValue); |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments