1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//! Worker Pool Management for FFT Parallelization
//!
//! This module provides a configurable thread pool for parallel FFT operations,
//! similar to SciPy's worker management functionality.
use scirs2_core::parallel_ops::*;
use std::env;
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
/// Configuration for FFT worker pool
#[derive(Debug, Clone)]
pub struct WorkerConfig {
/// Number of worker threads to use
pub num_workers: usize,
/// Whether parallelization is enabled
pub enabled: bool,
/// Stack size for worker threads (in bytes)
pub stack_size: Option<usize>,
/// Thread name prefix
pub thread_name_prefix: String,
}
impl Default for WorkerConfig {
fn default() -> Self {
// Default to using all available cores
let num_cpus = thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
// Check for environment variable override
let num_workers = env::var("SCIRS2_FFT_WORKERS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(num_cpus);
Self {
num_workers,
enabled: true,
stack_size: None,
thread_name_prefix: "scirs2-fft-worker".to_string(),
}
}
}
/// FFT Worker Pool Manager
/// Simplified to use core parallel abstractions instead of direct ThreadPool management
pub struct WorkerPool {
config: Arc<Mutex<WorkerConfig>>,
}
impl WorkerPool {
/// Create a new worker pool with default configuration
pub fn new() -> Self {
let config = WorkerConfig::default();
Self {
config: Arc::new(Mutex::new(config)),
}
}
/// Create a new worker pool with custom configuration
pub fn with_config(
config: WorkerConfig,
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
Ok(Self {
config: Arc::new(Mutex::new(config)),
})
}
// ThreadPool management removed - using core parallel abstractions instead
/// Get the current number of worker threads
pub fn get_workers(&self) -> usize {
self.config.lock().expect("Operation failed").num_workers
}
/// Set the number of worker threads
///
/// Update configuration - actual thread management handled by core parallel abstractions
pub fn set_workers(
&mut self,
num_workers: usize,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let mut config = self.config.lock().expect("Operation failed");
config.num_workers = num_workers;
Ok(())
}
/// Check if parallelization is enabled
pub fn is_enabled(&self) -> bool {
self.config.lock().expect("Operation failed").enabled
}
/// Enable or disable parallelization
pub fn set_enabled(&self, enabled: bool) {
self.config.lock().expect("Operation failed").enabled = enabled;
}
/// Execute a function in the worker pool if enabled
/// Simplified to use core parallel abstractions
pub fn execute<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R + Send,
R: Send,
{
// With core parallel abstractions, just execute the function
// The actual parallelism is handled by the core parallel_ops module
f()
}
/// Execute a function with a specific number of workers
/// Simplified to use core parallel abstractions
pub fn execute_with_workers<F, R>(&self, _numworkers: usize, f: F) -> R
where
F: FnOnce() -> R + Send,
R: Send,
{
// With core parallel abstractions, just execute the function
// The actual parallelism is handled by the core parallel_ops module
f()
}
/// Get information about the worker pool
pub fn get_info(&self) -> WorkerPoolInfo {
let config = self.config.lock().expect("Operation failed");
WorkerPoolInfo {
num_workers: config.num_workers,
enabled: config.enabled,
current_threads: num_threads(), // Use core parallel abstraction
thread_name_prefix: config.thread_name_prefix.clone(),
}
}
}
impl Default for WorkerPool {
fn default() -> Self {
Self::new()
}
}
/// Information about the worker pool state
#[derive(Debug, Clone)]
pub struct WorkerPoolInfo {
pub num_workers: usize,
pub enabled: bool,
pub current_threads: usize,
pub thread_name_prefix: String,
}
impl std::fmt::Display for WorkerPoolInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Worker Pool: {} workers (current: {}), enabled: {}, prefix: {}",
self.num_workers, self.current_threads, self.enabled, self.thread_name_prefix
)
}
}
/// Global worker pool instance
static GLOBAL_WORKER_POOL: OnceLock<WorkerPool> = OnceLock::new();
/// Get the global worker pool instance
#[allow(dead_code)]
pub fn get_global_pool() -> &'static WorkerPool {
GLOBAL_WORKER_POOL.get_or_init(WorkerPool::new)
}
/// Initialize the global worker pool with custom configuration
#[allow(dead_code)]
pub fn init_global_pool(config: WorkerConfig) -> Result<(), &'static str> {
GLOBAL_WORKER_POOL
.set(WorkerPool::with_config(config).map_err(|_| "Failed to create worker pool")?)
.map_err(|_| "Global worker pool already initialized")
}
/// Context manager for temporarily changing worker count
pub struct WorkerContext {
#[allow(dead_code)]
previous_workers: usize,
#[allow(dead_code)]
pool: &'static WorkerPool,
}
impl WorkerContext {
/// Create a new worker context with specified number of workers
pub fn new(_numworkers: usize) -> Self {
let pool = get_global_pool();
let previous_workers = pool.get_workers();
// Note: In a real implementation, we'd need to handle the Result here
// For now, we'll just use the existing pool if we can't create a new one
Self {
previous_workers,
pool,
}
}
}
impl Drop for WorkerContext {
fn drop(&mut self) {
// Reset to previous worker count
// Note: In a real implementation, we'd need to handle the Result here
}
}
/// Set the number of workers globally
#[allow(dead_code)]
pub fn set_workers(_n: usize) -> Result<(), &'static str> {
let _pool = get_global_pool();
// Note: This is a limitation of the current design - we can't modify a static reference
// In practice, you'd want a different approach or accept this limitation
Ok(())
}
/// Get the current number of workers
#[allow(dead_code)]
pub fn get_workers() -> usize {
get_global_pool().get_workers()
}
/// Execute a function with a specific number of workers temporarily
#[allow(dead_code)]
pub fn with_workers<F, R>(num_workers: usize, f: F) -> R
where
F: FnOnce() -> R + Send,
R: Send,
{
get_global_pool().execute_with_workers(num_workers, f)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_worker_pool() {
let pool = WorkerPool::new();
assert!(pool.get_workers() > 0);
assert!(pool.is_enabled());
}
#[test]
fn test_worker_config() {
let config = WorkerConfig {
num_workers: 4,
enabled: true,
stack_size: Some(2 * 1024 * 1024),
thread_name_prefix: "test-worker".to_string(),
};
let pool = WorkerPool::with_config(config).expect("Operation failed");
assert_eq!(pool.get_workers(), 4);
}
#[test]
fn test_enable_disable() {
let pool = WorkerPool::new();
assert!(pool.is_enabled());
pool.set_enabled(false);
assert!(!pool.is_enabled());
pool.set_enabled(true);
assert!(pool.is_enabled());
}
#[test]
fn test_execute() {
let pool = WorkerPool::new();
// Test with parallelization enabled
let result = pool.execute(|| 42);
assert_eq!(result, 42);
// Test with parallelization disabled
pool.set_enabled(false);
let result = pool.execute(|| 84);
assert_eq!(result, 84);
}
#[test]
fn test_execute_with_workers() {
let pool = WorkerPool::new();
let result = pool.execute_with_workers(2, || num_threads());
// With core parallel abstractions, execute_with_workers doesn't control
// the number of threads directly - it just executes the function
// The result should be the current number of threads from the runtime
if pool.is_enabled() {
assert!(result > 0);
}
}
#[test]
fn test_worker_info() {
let pool = WorkerPool::new();
let info = pool.get_info();
assert_eq!(info.num_workers, pool.get_workers());
assert_eq!(info.enabled, pool.is_enabled());
}
}