|
1 | 1 | import Foundation |
2 | 2 | import PythonKit |
3 | 3 |
|
4 | | -public var PyGILState_Guard: ((() throws -> Void) throws -> Void)! = nil |
| 4 | +public var gilStateEnsure: (() -> Any)! |
| 5 | +public var gilStateRelease: ((Any) -> Void)! |
| 6 | +func gilStateGuard<T>(_ closure: @escaping () throws -> T) throws -> T { |
| 7 | + let state = gilStateEnsure() |
| 8 | + do { |
| 9 | + let result = try closure() |
| 10 | + gilStateRelease(state) |
| 11 | + return result |
| 12 | + } catch { |
| 13 | + gilStateRelease(state) |
| 14 | + throw error |
| 15 | + } |
| 16 | +} |
5 | 17 |
|
6 | 18 | let pythonQueue = DispatchQueue(label: "Python Queue") |
7 | 19 |
|
8 | 20 | public func runPython<T>( |
9 | 21 | usePythonThread: Bool = false, |
10 | 22 | _ closure: @escaping () throws -> T |
11 | | -) async throws -> T { |
12 | | - return try await withUnsafeThrowingContinuation { con in |
13 | | - if usePythonThread { |
14 | | - PythonThread.shared.runPython { |
15 | | - do { |
16 | | - try PyGILState_Guard { |
17 | | - con.resume(returning: try closure()) |
18 | | - } |
19 | | - } catch let error as PythonError { |
20 | | - con.resume(throwing: ReadablePythonError(error)) |
21 | | - } catch { |
22 | | - con.resume(throwing: error) |
23 | | - } |
24 | | - } |
25 | | - } else { |
26 | | - pythonQueue.async { |
27 | | - do { |
28 | | - try PyGILState_Guard { |
29 | | - con.resume(returning: try closure()) |
30 | | - } |
31 | | - } catch let error as PythonError { |
32 | | - con.resume(throwing: ReadablePythonError(error)) |
33 | | - } catch { |
34 | | - con.resume(throwing: error) |
35 | | - } |
| 23 | +) throws -> T { |
| 24 | + if usePythonThread { |
| 25 | + return try PythonThread.shared.runPythonAndWait { |
| 26 | + return try gilStateGuard { |
| 27 | + try closure() |
36 | 28 | } |
37 | 29 | } |
| 30 | + } else { |
| 31 | + return try gilStateGuard { |
| 32 | + try closure() |
| 33 | + } |
38 | 34 | } |
39 | 35 | } |
40 | 36 |
|
@@ -66,5 +62,3 @@ public struct ReadablePythonError: Error, LocalizedError { |
66 | 62 | } |
67 | 63 | } |
68 | 64 |
|
69 | | - |
70 | | - |
0 commit comments