From 29b9547f11d5e3e61131898cb42e4ee7d24aa92e Mon Sep 17 00:00:00 2001 From: Ian Ker-Seymer Date: Fri, 27 Jan 2023 20:52:26 -0500 Subject: [PATCH] Disable thread support in libtest if RUST_TEST_THREADS=1 --- library/test/src/helpers/concurrency.rs | 30 ++++++++++++++++++++----- library/test/src/lib.rs | 5 ++--- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/library/test/src/helpers/concurrency.rs b/library/test/src/helpers/concurrency.rs index eb211157371b5..bc403c995724f 100644 --- a/library/test/src/helpers/concurrency.rs +++ b/library/test/src/helpers/concurrency.rs @@ -3,12 +3,30 @@ use std::{env, num::NonZeroUsize, thread}; pub fn get_concurrency() -> usize { - if let Ok(value) = env::var("RUST_TEST_THREADS") { - match value.parse::().ok() { - Some(n) => n.get(), - _ => panic!("RUST_TEST_THREADS is `{value}`, should be a positive integer."), - } + rust_test_threads_from_env() + .unwrap_or_else(|| thread::available_parallelism().map(|n| n.get()).unwrap_or(1)) +} + +pub fn supports_threads() -> bool { + if cfg!(target_os = "emscripten") || cfg!(target_family = "wasm") { + return false; + } + + // Accommodate libraries that may rely on shared thread-local storage (e.g. + // integrating with old C libraries). + if let Some(1) = rust_test_threads_from_env() { + return false; + } + + true +} + +fn rust_test_threads_from_env() -> Option { + let value = env::var("RUST_TEST_THREADS").ok()?; + + if let Ok(value) = value.parse::() { + Some(value.get()) } else { - thread::available_parallelism().map(|n| n.get()).unwrap_or(1) + panic!("RUST_TEST_THREADS is `{value}`, should be a positive integer.", value = value) } } diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 69fb529d7f563..6458fb72bdb36 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -82,7 +82,7 @@ mod tests; use core::any::Any; use event::{CompletedTest, TestEvent}; -use helpers::concurrency::get_concurrency; +use helpers::concurrency::{get_concurrency, supports_threads}; use helpers::exit_code::get_exit_code; use helpers::shuffle::{get_shuffle_seed, shuffle_tests}; use options::RunStrategy; @@ -592,8 +592,7 @@ pub fn run_test( // If the platform is single-threaded we're just going to run // the test synchronously, regardless of the concurrency // level. - let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm"); - if supports_threads { + if supports_threads() { let cfg = thread::Builder::new().name(name.as_slice().to_owned()); let mut runtest = Arc::new(Mutex::new(Some(runtest))); let runtest2 = runtest.clone();