|
| 1 | +use crate::pystate::attach_vm_to_thread; |
| 2 | +use core::ffi::c_int; |
| 3 | +use rustpython_vm::Interpreter; |
| 4 | +use rustpython_vm::vm::thread::ThreadedVirtualMachine; |
| 5 | +use std::sync::{Once, OnceLock, mpsc}; |
| 6 | + |
| 7 | +static VM_REQUEST_TX: OnceLock<mpsc::Sender<mpsc::SyncSender<ThreadedVirtualMachine>>> = |
| 8 | + OnceLock::new(); |
| 9 | +pub(crate) static INITIALIZED: Once = Once::new(); |
| 10 | + |
| 11 | +/// Request a vm from the main interpreter |
| 12 | +pub(crate) fn request_vm_from_interpreter() -> ThreadedVirtualMachine { |
| 13 | + let tx = VM_REQUEST_TX |
| 14 | + .get() |
| 15 | + .expect("VM request channel not initialized"); |
| 16 | + let (response_tx, response_rx) = mpsc::sync_channel(1); |
| 17 | + tx.send(response_tx).expect("Failed to send VM request"); |
| 18 | + response_rx.recv().expect("Failed to receive VM response") |
| 19 | +} |
| 20 | + |
| 21 | +#[unsafe(no_mangle)] |
| 22 | +pub extern "C" fn Py_IsInitialized() -> c_int { |
| 23 | + INITIALIZED.is_completed() as _ |
| 24 | +} |
| 25 | + |
| 26 | +#[unsafe(no_mangle)] |
| 27 | +pub extern "C" fn Py_Initialize() { |
| 28 | + Py_InitializeEx(0); |
| 29 | +} |
| 30 | + |
| 31 | +#[unsafe(no_mangle)] |
| 32 | +pub extern "C" fn Py_InitializeEx(_initsigs: c_int) { |
| 33 | + if INITIALIZED.is_completed() { |
| 34 | + panic!("Initialize called multiple times"); |
| 35 | + } |
| 36 | + |
| 37 | + INITIALIZED.call_once(|| { |
| 38 | + let (tx, rx) = mpsc::channel(); |
| 39 | + VM_REQUEST_TX |
| 40 | + .set(tx) |
| 41 | + .expect("VM request channel was already initialized"); |
| 42 | + |
| 43 | + std::thread::spawn(move || { |
| 44 | + let interp = Interpreter::with_init(Default::default(), |_vm| {}); |
| 45 | + interp.enter(|vm| { |
| 46 | + while let Ok(request) = rx.recv() { |
| 47 | + request |
| 48 | + .send(vm.new_thread()) |
| 49 | + .expect("Failed to send VM response"); |
| 50 | + } |
| 51 | + }) |
| 52 | + }); |
| 53 | + }); |
| 54 | + |
| 55 | + attach_vm_to_thread(); |
| 56 | +} |
| 57 | + |
| 58 | +#[unsafe(no_mangle)] |
| 59 | +pub extern "C" fn Py_Finalize() { |
| 60 | + let _ = Py_FinalizeEx(); |
| 61 | +} |
| 62 | + |
| 63 | +#[unsafe(no_mangle)] |
| 64 | +pub extern "C" fn Py_FinalizeEx() -> c_int { |
| 65 | + 0 |
| 66 | +} |
| 67 | + |
| 68 | +#[unsafe(no_mangle)] |
| 69 | +pub extern "C" fn Py_IsFinalizing() -> c_int { |
| 70 | + 0 |
| 71 | +} |
0 commit comments