pub(crate) use _multiprocessing::module_def;
#[cfg(any(unix, windows))]
const _: () = assert!(
core::mem::size_of::<rustpython_host_env::multiprocessing::SemHandle>()
== core::mem::size_of::<usize>()
&& core::mem::align_of::<rustpython_host_env::multiprocessing::SemHandle>()
== core::mem::align_of::<usize>()
);
#[cfg(any(unix, windows))]
#[repr(transparent)]
struct SemHandleWord(rustpython_host_env::multiprocessing::SemHandle);
#[cfg(any(unix, windows))]
impl core::ops::Deref for SemHandleWord {
type Target = rustpython_host_env::multiprocessing::SemHandle;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(any(unix, windows))]
impl core::fmt::Debug for SemHandleWord {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(f)
}
}
#[cfg(any(unix, windows))]
impl crate::vm::builtins::descriptor::MemberLayout for SemHandleWord {
const KIND: crate::vm::builtins::descriptor::MemberKind = {
if cfg!(all(windows, target_pointer_width = "64")) {
crate::vm::builtins::descriptor::MemberKind::ULongLong
} else {
crate::vm::builtins::descriptor::MemberKind::ULong
}
};
}
#[cfg(any(unix, windows))]
fn semlock_name(
name: Option<String>,
) -> (
Option<alloc::ffi::CString>,
crate::vm::builtins::descriptor::CStrMember,
) {
let Some(name) = name else {
return (
None,
crate::vm::builtins::descriptor::CStrMember::new(core::ptr::null()),
);
};
let owner = match alloc::ffi::CString::new(name) {
Ok(owner) => owner,
Err(err) => {
let bytes: Vec<u8> = err
.into_vec()
.into_iter()
.filter(|byte| *byte != 0)
.collect();
alloc::ffi::CString::new(bytes).unwrap_or_default()
}
};
let member = crate::vm::builtins::descriptor::CStrMember::new(owner.as_ptr());
(Some(owner), member)
}
#[cfg(windows)]
#[pymodule]
mod _multiprocessing {
use crate::vm::{
Context, FromArgs, Py, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyDict, PyType, PyTypeRef},
convert::ToPyException,
function::ArgBytesLike,
types::Constructor,
};
use core::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use rustpython_common::lock::PyMutex;
use rustpython_host_env::multiprocessing as host_multiprocessing;
#[derive(FromArgs)]
struct AcquireArgs {
#[pyarg(any, default = true)]
block: bool,
#[pyarg(any, optional)]
timeout: Option<crate::vm::PyObjectRef>,
}
#[derive(FromArgs)]
#[allow(dead_code)]
struct ExitArgs {
#[pyarg(positional, optional)]
exc_type: Option<crate::vm::PyObjectRef>,
#[pyarg(positional, optional)]
exc_value: Option<crate::vm::PyObjectRef>,
#[pyarg(positional, optional)]
exc_tb: Option<crate::vm::PyObjectRef>,
}
const RECURSIVE_MUTEX: i32 = 0;
const SEMAPHORE: i32 = 1;
macro_rules! ismine {
($self:expr) => {
$self.count.load(Ordering::Acquire) > 0
&& $self.last_tid.load(Ordering::Acquire)
== host_multiprocessing::current_thread_id()
};
}
#[derive(FromArgs)]
struct SemLockNewArgs {
#[pyarg(positional)]
kind: i32,
#[pyarg(positional)]
value: i32,
#[pyarg(positional)]
maxvalue: i32,
#[pyarg(positional)]
name: String,
#[pyarg(positional)]
unlink: bool,
}
#[pyattr]
#[pyclass(name = "SemLock", module = "_multiprocessing")]
#[derive(Debug, PyPayload)]
struct SemLock {
#[pymember]
handle: super::SemHandleWord,
#[pymember]
kind: i32,
#[pymember]
maxvalue: i32,
#[expect(dead_code, reason = "keeps the semaphore name allocation alive")]
name_owner: Option<alloc::ffi::CString>,
#[pymember]
name: crate::vm::builtins::descriptor::CStrMember,
last_tid: AtomicU32,
count: AtomicI32,
crit: PyMutex<()>,
}
type SemHandle = host_multiprocessing::SemHandle;
#[pyclass(with(Constructor), flags(BASETYPE))]
impl SemLock {
#[pymethod]
fn acquire(zelf: &Py<Self>, args: AcquireArgs, vm: &VirtualMachine) -> PyResult<bool> {
let blocking = args.block;
let timeout_obj = args.timeout;
let full_msecs: u32 = if !blocking {
0
} else if timeout_obj.as_ref().is_none_or(|o| vm.is_none(o)) {
host_multiprocessing::INFINITE_TIMEOUT
} else {
let timeout: f64 = timeout_obj.unwrap().try_float(vm)?.to_f64();
let timeout = timeout * 1000.0; if timeout < 0.0 {
0
} else if timeout >= 0.5 * host_multiprocessing::INFINITE_TIMEOUT as f64 {
return Err(vm.new_overflow_error("timeout is too large"));
} else {
(timeout + 0.5) as u32
}
};
{
let _crit = zelf.crit.lock();
if zelf.kind == RECURSIVE_MUTEX && ismine!(zelf) {
zelf.count.fetch_add(1, Ordering::Release);
return Ok(true);
}
match zelf.handle.wait(0) {
x if x == host_multiprocessing::wait_object_0() => {
zelf.last_tid
.store(host_multiprocessing::current_thread_id(), Ordering::Release);
zelf.count.fetch_add(1, Ordering::Release);
return Ok(true);
}
x if x == host_multiprocessing::wait_failed() => {
return Err(vm.new_last_os_error());
}
_ => {}
}
}
let poll_ms: u32 = 100;
let mut elapsed: u32 = 0;
loop {
let wait_ms = if full_msecs == host_multiprocessing::INFINITE_TIMEOUT {
poll_ms
} else {
let remaining = full_msecs.saturating_sub(elapsed);
if remaining == 0 {
return Ok(false);
}
remaining.min(poll_ms)
};
let handle = &zelf.handle;
let res = vm.allow_threads(|| handle.wait(wait_ms));
match res {
x if x == host_multiprocessing::wait_object_0() => {
let _crit = zelf.crit.lock();
zelf.last_tid
.store(host_multiprocessing::current_thread_id(), Ordering::Release);
zelf.count.fetch_add(1, Ordering::Release);
return Ok(true);
}
x if x == host_multiprocessing::wait_timeout() => {
vm.check_signals()?;
if full_msecs != host_multiprocessing::INFINITE_TIMEOUT {
elapsed = elapsed.saturating_add(wait_ms);
}
}
x if x == host_multiprocessing::wait_failed() => {
return Err(vm.new_last_os_error());
}
_ => {
return Err(vm.new_runtime_error(format!(
"WaitForSingleObject() gave unrecognized value {res}"
)));
}
}
}
}
#[pymethod]
fn release(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
let _crit = zelf.crit.lock();
if zelf.kind == RECURSIVE_MUTEX {
if !ismine!(zelf) {
return Err(vm.new_assertion_error(
"attempt to release recursive lock not owned by thread",
));
}
if zelf.count.load(Ordering::Acquire) > 1 {
zelf.count.fetch_sub(1, Ordering::Release);
return Ok(());
}
}
if let Err(err) = zelf.handle.release() {
if host_multiprocessing::is_too_many_posts(err) {
return Err(vm.new_value_error("semaphore or lock released too many times"));
}
return Err(vm.new_last_os_error());
}
zelf.count.fetch_sub(1, Ordering::Release);
Ok(())
}
#[pymethod(name = "__enter__")]
fn enter(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<bool> {
Self::acquire(
zelf,
AcquireArgs {
block: true,
timeout: None,
},
vm,
)
}
#[pymethod]
fn __exit__(zelf: &Py<Self>, _args: ExitArgs, vm: &VirtualMachine) -> PyResult<()> {
Self::release(zelf, vm)
}
#[pyclassmethod(name = "_rebuild")]
fn rebuild(
cls: PyTypeRef,
handle: isize,
kind: i32,
maxvalue: i32,
name: Option<String>,
vm: &VirtualMachine,
) -> PyResult {
let (name_owner, name_member) = super::semlock_name(name);
let zelf = Self {
handle: super::SemHandleWord(SemHandle::from_raw(
handle as host_multiprocessing::RawHandle,
)),
kind,
maxvalue,
name_owner,
name: name_member,
last_tid: AtomicU32::new(0),
count: AtomicI32::new(0),
crit: PyMutex::new(()),
};
zelf.into_ref_with_type(vm, cls).map(Into::into)
}
#[pymethod]
fn _after_fork(zelf: &Py<Self>) {
let _crit = zelf.crit.lock();
zelf.count.store(0, Ordering::Release);
zelf.last_tid.store(0, Ordering::Release);
}
#[pymethod]
fn __reduce__(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("cannot pickle 'SemLock' object"))
}
#[pymethod]
fn _count(zelf: &Py<Self>) -> i32 {
let _crit = zelf.crit.lock();
zelf.count.load(Ordering::Acquire)
}
#[pymethod]
fn _is_mine(zelf: &Py<Self>) -> bool {
ismine!(zelf)
}
#[pymethod]
fn _get_value(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<i32> {
zelf.handle.value().map_err(|_| vm.new_last_os_error())
}
#[pymethod]
fn _is_zero(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<bool> {
let val = zelf.handle.value().map_err(|_| vm.new_last_os_error())?;
Ok(val == 0)
}
#[extend_class]
fn extend_class(ctx: &Context, class: &Py<PyType>) {
class.set_attr(
ctx.intern_str("RECURSIVE_MUTEX"),
ctx.new_int(RECURSIVE_MUTEX).into(),
);
class.set_attr(ctx.intern_str("SEMAPHORE"), ctx.new_int(SEMAPHORE).into());
class.set_attr(
ctx.intern_str("SEM_VALUE_MAX"),
ctx.new_int(i32::MAX).into(),
);
}
}
impl Constructor for SemLock {
type Args = SemLockNewArgs;
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
if args.kind != RECURSIVE_MUTEX && args.kind != SEMAPHORE {
return Err(vm.new_value_error("unrecognized kind"));
}
if args.maxvalue <= 0 {
return Err(vm.new_value_error("maxvalue must be positive"));
}
if args.value < 0 || args.value > args.maxvalue {
return Err(vm.new_value_error("invalid value"));
}
let handle = super::SemHandleWord(
SemHandle::create(args.value, args.maxvalue).map_err(|e| e.to_pyexception(vm))?,
);
let (name_owner, name) =
super::semlock_name(if args.unlink { None } else { Some(args.name) });
Ok(Self {
handle,
kind: args.kind,
maxvalue: args.maxvalue,
name_owner,
name,
last_tid: AtomicU32::new(0),
count: AtomicI32::new(0),
crit: PyMutex::new(()),
})
}
}
#[pyfunction]
fn sem_unlink(_name: String) {}
#[pyattr]
fn flags(vm: &VirtualMachine) -> PyRef<PyDict> {
vm.ctx.new_dict()
}
#[pyfunction]
fn closesocket(socket: usize, vm: &VirtualMachine) -> PyResult<()> {
host_multiprocessing::close_socket(socket as host_multiprocessing::RawSocket)
.map_err(|_| vm.new_last_os_error())
}
#[pyfunction]
fn recv(socket: usize, size: usize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
host_multiprocessing::recv_socket(socket as host_multiprocessing::RawSocket, size)
.map_err(|_| vm.new_last_os_error())
}
#[pyfunction]
fn send(socket: usize, buf: ArgBytesLike, vm: &VirtualMachine) -> PyResult<core::ffi::c_int> {
buf.with_ref(|b| {
host_multiprocessing::send_socket(socket as host_multiprocessing::RawSocket, b)
})
.map_err(|_| vm.new_last_os_error())
}
}
#[cfg(unix)]
#[pymodule]
mod _multiprocessing {
use crate::vm::{
Context, FromArgs, Py, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyDict, PyType, PyTypeRef},
convert::ToPyException,
types::Constructor,
};
use core::sync::atomic::{AtomicI32, AtomicU64, Ordering};
use rustpython_common::lock::PyMutex;
use rustpython_host_env::multiprocessing::{
self as host_multiprocessing, SemError, TryAcquireStatus, WaitStatus,
};
use rustpython_vm::exceptions;
#[derive(FromArgs)]
struct AcquireArgs {
#[pyarg(any, default = true)]
block: bool,
#[pyarg(any, optional)]
timeout: Option<crate::vm::PyObjectRef>,
}
#[derive(FromArgs)]
#[allow(dead_code)]
struct ExitArgs {
#[pyarg(positional, optional)]
exc_type: Option<crate::vm::PyObjectRef>,
#[pyarg(positional, optional)]
exc_value: Option<crate::vm::PyObjectRef>,
#[pyarg(positional, optional)]
exc_tb: Option<crate::vm::PyObjectRef>,
}
#[cfg(target_vendor = "apple")]
enum SemWaitError {
Timeout,
SignalException(PyBaseExceptionRef),
OsError(SemError),
}
#[cfg(target_vendor = "apple")]
fn sem_timedwait_polled(
handle: &SemHandle,
deadline: &host_multiprocessing::Deadline,
vm: &VirtualMachine,
) -> Result<(), SemWaitError> {
let mut delay: u64 = 0;
loop {
match vm.allow_threads(|| handle.poll_wait_step(deadline, delay)) {
Ok(host_multiprocessing::PollWaitStep::Acquired) => return Ok(()),
Ok(host_multiprocessing::PollWaitStep::Timeout) => {
return Err(SemWaitError::Timeout);
}
Ok(host_multiprocessing::PollWaitStep::Continue(next_delay)) => {
delay = next_delay;
}
Err(err) => return Err(SemWaitError::OsError(err)),
}
if let Err(exc) = vm.check_signals() {
return Err(SemWaitError::SignalException(exc));
}
}
}
const RECURSIVE_MUTEX: i32 = 0;
const SEMAPHORE: i32 = 1;
macro_rules! ismine {
($self:expr) => {
$self.count.load(Ordering::Acquire) > 0
&& $self.last_tid.load(Ordering::Acquire)
== host_multiprocessing::current_thread_id()
};
}
#[derive(FromArgs)]
struct SemLockNewArgs {
#[pyarg(positional)]
kind: i32,
#[pyarg(positional)]
value: i32,
#[pyarg(positional)]
maxvalue: i32,
#[pyarg(positional)]
name: String,
#[pyarg(positional)]
unlink: bool,
}
#[pyattr]
#[pyclass(name = "SemLock", module = "_multiprocessing")]
#[derive(Debug, PyPayload)]
struct SemLock {
#[pymember]
handle: super::SemHandleWord,
#[pymember]
kind: i32,
#[pymember]
maxvalue: i32,
#[expect(dead_code, reason = "keeps the semaphore name allocation alive")]
name_owner: Option<alloc::ffi::CString>,
#[pymember]
name: crate::vm::builtins::descriptor::CStrMember,
last_tid: AtomicU64, count: AtomicI32, crit: PyMutex<()>,
}
type SemHandle = host_multiprocessing::SemHandle;
#[pyclass(with(Constructor), flags(BASETYPE))]
impl SemLock {
#[pymethod]
fn acquire(zelf: &Py<Self>, args: AcquireArgs, vm: &VirtualMachine) -> PyResult<bool> {
let blocking = args.block;
let timeout_obj = args.timeout;
let _crit = zelf.crit.lock();
if zelf.kind == RECURSIVE_MUTEX && ismine!(zelf) {
zelf.count.fetch_add(1, Ordering::Release);
return Ok(true);
}
let use_deadline = timeout_obj.as_ref().is_some_and(|o| !vm.is_none(o));
let deadline = if use_deadline {
let timeout_obj = timeout_obj.unwrap();
let timeout: f64 = timeout_obj.try_float(vm)?.to_f64();
Some(
host_multiprocessing::deadline_from_timeout(timeout)
.map_err(|_| vm.new_os_error("gettimeofday failed"))?,
)
} else {
None
};
let try_status = loop {
match zelf.handle.trywait() {
TryAcquireStatus::Interrupted => {
vm.check_signals()?;
}
status => break status,
}
};
if matches!(try_status, TryAcquireStatus::WouldBlock) && blocking {
drop(_crit);
#[cfg(not(target_vendor = "apple"))]
{
loop {
let handle = &zelf.handle;
match vm.allow_threads(|| handle.wait(deadline.as_ref())) {
WaitStatus::Acquired => break,
WaitStatus::Interrupted => {
vm.check_signals()?;
continue;
}
WaitStatus::TimedOut => return Ok(false),
WaitStatus::Error(err) => return Err(os_error(vm, err)),
}
}
}
#[cfg(target_vendor = "apple")]
{
if let Some(ref dl) = deadline {
match sem_timedwait_polled(&zelf.handle, dl, vm) {
Ok(()) => {}
Err(SemWaitError::Timeout) => {
return Ok(false);
}
Err(SemWaitError::SignalException(exc)) => {
return Err(exc);
}
Err(SemWaitError::OsError(e)) => {
return Err(os_error(vm, e));
}
}
} else {
loop {
let handle = &zelf.handle;
match vm.allow_threads(|| handle.wait(None)) {
WaitStatus::Acquired => break,
WaitStatus::Interrupted => {
vm.check_signals()?;
continue;
}
WaitStatus::TimedOut => return Ok(false),
WaitStatus::Error(err) => return Err(os_error(vm, err)),
}
}
}
}
let _crit = zelf.crit.lock();
zelf.mark_acquired();
return Ok(true);
} else if !matches!(try_status, TryAcquireStatus::Acquired) {
match try_status {
TryAcquireStatus::WouldBlock => return Ok(false),
TryAcquireStatus::Interrupted => return vm.check_signals().map(|_| false),
TryAcquireStatus::Error(err) => return Err(os_error(vm, err)),
TryAcquireStatus::Acquired => unreachable!(),
}
}
zelf.mark_acquired();
Ok(true)
}
fn mark_acquired(&self) {
self.count.fetch_add(1, Ordering::Release);
self.last_tid
.store(host_multiprocessing::current_thread_id(), Ordering::Release);
}
#[pymethod]
fn release(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
let _crit = zelf.crit.lock();
if zelf.kind == RECURSIVE_MUTEX {
if !ismine!(zelf) {
return Err(vm.new_assertion_error(
"attempt to release recursive lock not owned by thread",
));
}
if zelf.count.load(Ordering::Acquire) > 1 {
zelf.count.fetch_sub(1, Ordering::Release);
return Ok(());
}
} else {
#[cfg(not(target_vendor = "apple"))]
{
let sval = zelf.handle.value().map_err(|err| os_error(vm, err))?;
if sval >= zelf.maxvalue {
return Err(vm.new_value_error("semaphore or lock released too many times"));
}
}
#[cfg(target_vendor = "apple")]
{
if zelf.maxvalue == 1 {
match zelf.handle.trywait() {
TryAcquireStatus::WouldBlock => {}
TryAcquireStatus::Acquired => {
if let Err(err) = zelf.handle.post() {
return Err(os_error(vm, err));
}
return Err(
vm.new_value_error("semaphore or lock released too many times")
);
}
TryAcquireStatus::Interrupted => {
return Err(os_error(vm, SemError::Interrupted));
}
TryAcquireStatus::Error(err) => return Err(os_error(vm, err)),
}
}
}
}
if let Err(err) = zelf.handle.post() {
return Err(os_error(vm, err));
}
zelf.count.fetch_sub(1, Ordering::Release);
Ok(())
}
#[pymethod(name = "__enter__")]
fn enter(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<bool> {
Self::acquire(
zelf,
AcquireArgs {
block: true,
timeout: None,
},
vm,
)
}
#[pymethod]
fn __exit__(zelf: &Py<Self>, _args: ExitArgs, vm: &VirtualMachine) -> PyResult<()> {
Self::release(zelf, vm)
}
#[pyclassmethod(name = "_rebuild")]
fn rebuild(
cls: PyTypeRef,
_handle: isize,
kind: i32,
maxvalue: i32,
name: Option<String>,
vm: &VirtualMachine,
) -> PyResult {
let Some(ref name_str) = name else {
return Err(vm.new_value_error("cannot rebuild SemLock without name"));
};
let handle = super::SemHandleWord(
SemHandle::open_existing(name_str).map_err(|err| os_error(vm, err))?,
);
let (name_owner, name) = super::semlock_name(name);
let zelf = Self {
handle,
kind,
maxvalue,
name_owner,
name,
last_tid: AtomicU64::new(0),
count: AtomicI32::new(0),
crit: PyMutex::new(()),
};
zelf.into_ref_with_type(vm, cls).map(Into::into)
}
#[pymethod]
fn _after_fork(zelf: &Py<Self>) {
let _crit = zelf.crit.lock();
zelf.count.store(0, Ordering::Release);
zelf.last_tid.store(0, Ordering::Release);
}
#[pymethod]
fn __reduce__(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("cannot pickle 'SemLock' object"))
}
#[pymethod]
fn _count(zelf: &Py<Self>) -> i32 {
let _crit = zelf.crit.lock();
zelf.count.load(Ordering::Acquire)
}
#[pymethod]
fn _is_mine(zelf: &Py<Self>) -> bool {
ismine!(zelf)
}
#[pymethod]
fn _get_value(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<i32> {
#[cfg(target_vendor = "apple")]
let _ = zelf;
#[cfg(not(target_vendor = "apple"))]
{
zelf.handle.value().map_err(|err| os_error(vm, err))
}
#[cfg(target_vendor = "apple")]
{
Err(vm.new_not_implemented_error(String::new()))
}
}
#[pymethod]
fn _is_zero(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<bool> {
#[cfg(not(target_vendor = "apple"))]
{
Ok(Self::_get_value(zelf, vm)? == 0)
}
#[cfg(target_vendor = "apple")]
{
match zelf.handle.trywait() {
TryAcquireStatus::WouldBlock => return Ok(true),
TryAcquireStatus::Interrupted => {
return Err(os_error(vm, SemError::Interrupted));
}
TryAcquireStatus::Error(err) => return Err(os_error(vm, err)),
TryAcquireStatus::Acquired => {}
}
if let Err(err) = zelf.handle.post() {
return Err(os_error(vm, err));
}
Ok(false)
}
}
#[extend_class]
fn extend_class(ctx: &Context, class: &Py<PyType>) {
class.set_attr(
ctx.intern_str("RECURSIVE_MUTEX"),
ctx.new_int(RECURSIVE_MUTEX).into(),
);
class.set_attr(ctx.intern_str("SEMAPHORE"), ctx.new_int(SEMAPHORE).into());
let sem_value_max = host_multiprocessing::sem_value_max();
class.set_attr(
ctx.intern_str("SEM_VALUE_MAX"),
ctx.new_int(sem_value_max).into(),
);
}
}
impl Constructor for SemLock {
type Args = SemLockNewArgs;
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
if args.kind != RECURSIVE_MUTEX && args.kind != SEMAPHORE {
return Err(vm.new_value_error("unrecognized kind"));
}
if args.value < 0 || args.value > args.maxvalue {
return Err(vm.new_value_error("invalid value"));
}
let value = args.value as u32;
let (handle, name) =
SemHandle::create(&args.name, value, args.unlink).map_err(|err| {
if err == SemError::InteriorNul {
exceptions::nul_char_error(vm)
} else {
os_error(vm, err)
}
})?;
let (name_owner, name) = super::semlock_name(name);
Ok(Self {
handle: super::SemHandleWord(handle),
kind: args.kind,
maxvalue: args.maxvalue,
name_owner,
name,
last_tid: AtomicU64::new(0),
count: AtomicI32::new(0),
crit: PyMutex::new(()),
})
}
}
#[pyfunction]
fn sem_unlink(name: String, vm: &VirtualMachine) -> PyResult<()> {
host_multiprocessing::sem_unlink(&name).map_err(|err| {
if err == SemError::InteriorNul {
exceptions::nul_char_error(vm)
} else {
os_error(vm, err)
}
})
}
#[pyattr]
fn flags(vm: &VirtualMachine) -> PyRef<PyDict> {
let flags = vm.ctx.new_dict();
flags
.set_item("HAVE_SEM_OPEN", vm.ctx.new_int(1).into(), vm)
.unwrap();
#[cfg(not(target_vendor = "apple"))]
{
flags
.set_item("HAVE_SEM_TIMEDWAIT", vm.ctx.new_int(1).into(), vm)
.unwrap();
}
#[cfg(target_vendor = "apple")]
{
flags
.set_item("HAVE_BROKEN_SEM_GETVALUE", vm.ctx.new_int(1).into(), vm)
.unwrap();
}
flags
}
fn os_error(vm: &VirtualMachine, err: SemError) -> PyBaseExceptionRef {
err.to_pyexception(vm)
}
}
#[cfg(all(not(unix), not(windows)))]
#[pymodule]
mod _multiprocessing {}