From d7acde2b42bc720397777d6556f94b4e967e1bae Mon Sep 17 00:00:00 2001 From: Stephan Seitz Date: Thu, 2 Apr 2026 09:18:48 +0200 Subject: [PATCH] fix: ensure lock is hold when loading library Otherwise two threads might race to load a library at the same time. This would be a problem when the global gets init twice and two reader threads get different library handles from which one gets dropped. --- trtx/src/lib.rs | 84 ++++++++++++++++++++++++++----------------------- 1 file changed, 44 insertions(+), 40 deletions(-) diff --git a/trtx/src/lib.rs b/trtx/src/lib.rs index 115c342..23deb9b 100644 --- a/trtx/src/lib.rs +++ b/trtx/src/lib.rs @@ -169,27 +169,29 @@ pub fn dynamically_load_tensorrt(_filename: Option) -> Result<( if TRTLIB.read()?.is_some() { return Ok(()); } - let lib = if let Some(filename) = _filename { - unsafe { libloading::Library::new(filename) } - } else { - unsafe { - libloading::Library::new(if cfg!(unix) { - if cfg!(feature = "v_1_4") { - "libtensorrt_rtx.so.1.4.0" + let mut write = TRTLIB.write()?; + if write.is_none() { + let lib = if let Some(filename) = _filename { + unsafe { libloading::Library::new(filename) } + } else { + unsafe { + libloading::Library::new(if cfg!(unix) { + if cfg!(feature = "v_1_4") { + "libtensorrt_rtx.so.1.4.0" + } else { + "libtensorrt_rtx.so.1.3.0" + } } else { - "libtensorrt_rtx.so.1.3.0" - } - } else { - if cfg!(feature = "v_1_4") { - "tensorrt_rtx_1_4.dll" - } else { - "tensorrt_rtx_1_3.dll" - } - }) - } - }?; - - *TRTLIB.write()? = Some(lib); + if cfg!(feature = "v_1_4") { + "tensorrt_rtx_1_4.dll" + } else { + "tensorrt_rtx_1_3.dll" + } + }) + } + }?; + *write = Some(lib); + } } Ok(()) } @@ -206,27 +208,29 @@ pub fn dynamically_load_tensorrt_onnxparser(_filename: Option) if TRT_ONNXPARSER_LIB.read()?.is_some() { return Ok(()); } - let lib = if let Some(filename) = _filename { - unsafe { libloading::Library::new(filename) } - } else { - unsafe { - libloading::Library::new(if cfg!(unix) { - if cfg!(feature = "v_1_4") { - "libtensorrt_onnxparser_rtx.so.1.4.0" + let mut write = TRT_ONNXPARSER_LIB.write()?; + if write.is_none() { + let lib = if let Some(filename) = _filename { + unsafe { libloading::Library::new(filename) } + } else { + unsafe { + libloading::Library::new(if cfg!(unix) { + if cfg!(feature = "v_1_4") { + "libtensorrt_onnxparser_rtx.so.1.4.0" + } else { + "libtensorrt_onnxparser_rtx.so.1.3.0" + } } else { - "libtensorrt_onnxparser_rtx.so.1.3.0" - } - } else { - if cfg!(feature = "v_1_4") { - "tensorrt_onnxparser_rtx_1_4.dll" - } else { - "tensorrt_onnxparser_rtx_1_3.dll" - } - }) - } - }?; - - *TRT_ONNXPARSER_LIB.write()? = Some(lib); + if cfg!(feature = "v_1_4") { + "tensorrt_onnxparser_rtx_1_4.dll" + } else { + "tensorrt_onnxparser_rtx_1_3.dll" + } + }) + } + }?; + *write = Some(lib); + } } Ok(()) }