Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use rayon::prelude::*;
use rust_stemmers::{Algorithm, Stemmer};
use std::sync::atomic::{AtomicU32, Ordering};

/// PID of the process that started rayon's global thread pool. A fork()ed child inherits
/// the pool's state but not its threads, so handing it work there would block forever.
static RAYON_PID: AtomicU32 = AtomicU32::new(0);

fn rayon_usable() -> bool {
let pid = std::process::id();
match RAYON_PID.compare_exchange(0, pid, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => true,
Err(owner) => owner == pid,
}
}

const SUPPORTED_LANGUAGES: &[(&str, Algorithm)] = &[
("arabic", Algorithm::Arabic),
Expand Down Expand Up @@ -60,6 +73,9 @@ impl SnowballStemmer {

#[inline(always)]
pub fn stem_words_parallel(&self, inputs: Vec<String>) -> Vec<String> {
if !rayon_usable() {
return self.stem_words(inputs);
}
inputs
.into_par_iter()
.map(|word| self.stemmer.stem(&word).into_owned())
Expand Down
29 changes: 29 additions & 0 deletions tests/test_py_rust_stemers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import os
import signal
import time
import warnings

import pytest

import py_rust_stemmers
Expand Down Expand Up @@ -27,6 +32,30 @@ def test_parallel_matches_sequential(english):
assert english.stem_words_parallel(words) == english.stem_words(words)


@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork")
def test_stem_words_parallel_in_forked_child(english):
words = ["fruitlessly", "happiness", "computations"] * 1000
expected = english.stem_words_parallel(words) # starts rayon's thread pool in this process
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning) # fork() in a multi-threaded process
pid = os.fork()
if pid == 0: # child: never return into pytest
try:
os._exit(0 if english.stem_words_parallel(words) == expected else 1)
finally:
os._exit(1)
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
done, status = os.waitpid(pid, os.WNOHANG)
if done:
assert os.waitstatus_to_exitcode(status) == 0
return
time.sleep(0.05)
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
pytest.fail("stem_words_parallel hung in a forked child")


def test_spanish_stem_words():
stemmer = py_rust_stemmers.SnowballStemmer("spanish")
words = ["frutalmente", "felicidad", "computaciones"]
Expand Down