pub struct ThreadingConfig {
pub num_threads: usize,
pub min_work_size: usize,
pub max_work_per_thread: usize,
pub timeout: Duration,
pub enable_affinity: bool,
pub affinity_strategy: AffinityStrategy,
}Expand description
Thread-safe configuration for multi-threading operations
Fields§
§num_threads: usizeNumber of worker threads to use
min_work_size: usizeMinimum work size to trigger multi-threading
max_work_per_thread: usizeMaximum work size per thread
timeout: DurationThread pool timeout
enable_affinity: boolEnable thread affinity for better cache performance
affinity_strategy: AffinityStrategyThread affinity strategy
Implementations§
Source§impl ThreadingConfig
impl ThreadingConfig
Sourcepub fn security_optimized() -> Self
pub fn security_optimized() -> Self
Create a security-optimized configuration
Examples found in repository?
examples/multithreading_usage.rs (line 36)
21fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
22 #[cfg(feature = "multithreading")]
23 {
24 println!("=== lib-Q Multi-threading Example ===\n");
25
26 // Example 1: Basic multi-threading configuration
27 println!("1. Basic Multi-threading Configuration");
28 println!("=====================================");
29
30 let config = ThreadingConfig::default();
31 println!(
32 "Default config: {} threads, min work size: {} bytes",
33 config.num_threads, config.min_work_size
34 );
35
36 let security_config = ThreadingConfig::security_optimized();
37 println!(
38 "Security config: {} threads (single-threaded for maximum security)",
39 security_config.num_threads
40 );
41
42 let performance_config = ThreadingConfig::performance_optimized();
43 println!(
44 "Performance config: {} threads, min work size: {} bytes",
45 performance_config.num_threads, performance_config.min_work_size
46 );
47
48 let balanced_config = ThreadingConfig::balanced();
49 println!(
50 "Balanced config: {} threads, min work size: {} bytes",
51 balanced_config.num_threads, balanced_config.min_work_size
52 );
53 println!();
54
55 // Example 2: Initialize global thread pool
56 println!("2. Global Thread Pool Initialization");
57 println!("====================================");
58
59 init_global_thread_pool(balanced_config.clone());
60 println!("Global thread pool initialized with balanced configuration");
61 println!();
62
63 // Example 3: Process small workload (sequential fallback)
64 println!("3. Small Workload Processing (Sequential Fallback)");
65 println!("==================================================");
66
67 let small_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10]; // Small workload
68 let start = Instant::now();
69
70 let results = process_keccak_states_global(&small_states, OptimizationLevel::Reference)?;
71 let duration = start.elapsed();
72
73 println!(
74 "Processed {} states in {:?} (sequential mode due to small workload)",
75 small_states.len(),
76 duration
77 );
78 println!("Results: {} processed states", results.len());
79 println!();
80
81 // Example 4: Process large workload (multi-threaded)
82 println!("4. Large Workload Processing (Multi-threaded)");
83 println!("=============================================");
84
85 let large_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10000]; // Large workload
86 let start = Instant::now();
87
88 let results = process_keccak_states_global(&large_states, OptimizationLevel::Maximum)?;
89 let duration = start.elapsed();
90
91 println!(
92 "Processed {} states in {:?} (multi-threaded mode)",
93 large_states.len(),
94 duration
95 );
96 println!("Results: {} processed states", results.len());
97 println!();
98
99 // Example 5: Custom thread pool with different configurations
100 println!("5. Custom Thread Pool with Different Configurations");
101 println!("===================================================");
102
103 // Security-optimized pool
104 let security_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
105 let security_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
106 let start = Instant::now();
107
108 let _security_results =
109 security_pool.process_keccak_states(&security_states, OptimizationLevel::Reference)?;
110 let security_duration = start.elapsed();
111
112 println!(
113 "Security pool: {} states in {:?} (single-threaded)",
114 security_states.len(),
115 security_duration
116 );
117
118 // Performance-optimized pool
119 let performance_pool = CryptoThreadPool::new(ThreadingConfig::performance_optimized());
120 let performance_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
121 let start = Instant::now();
122
123 let _performance_results = performance_pool
124 .process_keccak_states(&performance_states, OptimizationLevel::Maximum)?;
125 let performance_duration = start.elapsed();
126
127 println!(
128 "Performance pool: {} states in {:?} (multi-threaded)",
129 performance_states.len(),
130 performance_duration
131 );
132 println!();
133
134 // Example 6: Direct multi-threading function usage
135 println!("6. Direct Multi-threading Function Usage");
136 println!("========================================");
137
138 let direct_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
139 let start = Instant::now();
140
141 let direct_results = p1600_multithreaded(&direct_states, OptimizationLevel::Advanced)?;
142 let direct_duration = start.elapsed();
143
144 println!(
145 "Direct function: {} states in {:?}",
146 direct_states.len(),
147 direct_duration
148 );
149 println!("Results: {} processed states", direct_results.len());
150 println!();
151
152 // Example 7: Performance comparison
153 println!("7. Performance Comparison");
154 println!("=========================");
155
156 let test_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
157
158 // Sequential processing
159 let start = Instant::now();
160 let sequential_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
161 let _sequential_results =
162 sequential_pool.process_keccak_states(&test_states, OptimizationLevel::Reference)?;
163 let sequential_duration = start.elapsed();
164
165 // Multi-threaded processing
166 let start = Instant::now();
167 let _multi_results =
168 process_keccak_states_global(&test_states, OptimizationLevel::Maximum)?;
169 let multi_duration = start.elapsed();
170
171 println!("Sequential: {:?}", sequential_duration);
172 println!("Multi-threaded: {:?}", multi_duration);
173
174 if multi_duration < sequential_duration {
175 let speedup = sequential_duration.as_nanos() as f64 / multi_duration.as_nanos() as f64;
176 println!("Speedup: {:.2}x", speedup);
177 } else {
178 println!("Sequential processing was faster (likely due to overhead)");
179 }
180 println!();
181
182 // Example 8: Error handling and graceful degradation
183 println!("8. Error Handling and Graceful Degradation");
184 println!("===========================================");
185
186 // Test with invalid configuration (should fall back to sequential)
187 let invalid_config = ThreadingConfig {
188 num_threads: 0, // Invalid: no threads
189 min_work_size: 100,
190 max_work_per_thread: 1000,
191 timeout: std::time::Duration::from_secs(5),
192 enable_affinity: false,
193 affinity_strategy: lib_q_keccak::AffinityStrategy::Disabled,
194 };
195
196 let fallback_pool = CryptoThreadPool::new(invalid_config);
197 let fallback_states: Vec<[u64; 25]> = vec![[0u64; 25]; 100];
198 let start = Instant::now();
199
200 match fallback_pool.process_keccak_states(&fallback_states, OptimizationLevel::Reference) {
201 Ok(results) => {
202 let duration = start.elapsed();
203 println!(
204 "Fallback successful: {} states in {:?} (sequential fallback)",
205 fallback_states.len(),
206 duration
207 );
208 println!("Results: {} processed states", results.len());
209 }
210 Err(e) => {
211 println!("Fallback failed: {}", e);
212 }
213 }
214 println!();
215
216 println!("=== Multi-threading Example Complete ===");
217 println!("All operations completed successfully!");
218 }
219
220 #[cfg(not(feature = "multithreading"))]
221 {
222 println!("Multi-threading feature not enabled.");
223 println!("Enable with: cargo run --example multithreading_usage --features multithreading");
224 println!();
225 println!("This example demonstrates:");
226 println!("- Thread-safe cryptographic operations");
227 println!("- Configurable thread pools for different use cases");
228 println!("- Performance vs. security trade-offs");
229 println!("- Graceful fallback to sequential processing");
230 println!("- Error handling and timeout management");
231 }
232
233 Ok(())
234}Sourcepub fn performance_optimized() -> Self
pub fn performance_optimized() -> Self
Create a performance-optimized configuration
Examples found in repository?
examples/multithreading_usage.rs (line 42)
21fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
22 #[cfg(feature = "multithreading")]
23 {
24 println!("=== lib-Q Multi-threading Example ===\n");
25
26 // Example 1: Basic multi-threading configuration
27 println!("1. Basic Multi-threading Configuration");
28 println!("=====================================");
29
30 let config = ThreadingConfig::default();
31 println!(
32 "Default config: {} threads, min work size: {} bytes",
33 config.num_threads, config.min_work_size
34 );
35
36 let security_config = ThreadingConfig::security_optimized();
37 println!(
38 "Security config: {} threads (single-threaded for maximum security)",
39 security_config.num_threads
40 );
41
42 let performance_config = ThreadingConfig::performance_optimized();
43 println!(
44 "Performance config: {} threads, min work size: {} bytes",
45 performance_config.num_threads, performance_config.min_work_size
46 );
47
48 let balanced_config = ThreadingConfig::balanced();
49 println!(
50 "Balanced config: {} threads, min work size: {} bytes",
51 balanced_config.num_threads, balanced_config.min_work_size
52 );
53 println!();
54
55 // Example 2: Initialize global thread pool
56 println!("2. Global Thread Pool Initialization");
57 println!("====================================");
58
59 init_global_thread_pool(balanced_config.clone());
60 println!("Global thread pool initialized with balanced configuration");
61 println!();
62
63 // Example 3: Process small workload (sequential fallback)
64 println!("3. Small Workload Processing (Sequential Fallback)");
65 println!("==================================================");
66
67 let small_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10]; // Small workload
68 let start = Instant::now();
69
70 let results = process_keccak_states_global(&small_states, OptimizationLevel::Reference)?;
71 let duration = start.elapsed();
72
73 println!(
74 "Processed {} states in {:?} (sequential mode due to small workload)",
75 small_states.len(),
76 duration
77 );
78 println!("Results: {} processed states", results.len());
79 println!();
80
81 // Example 4: Process large workload (multi-threaded)
82 println!("4. Large Workload Processing (Multi-threaded)");
83 println!("=============================================");
84
85 let large_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10000]; // Large workload
86 let start = Instant::now();
87
88 let results = process_keccak_states_global(&large_states, OptimizationLevel::Maximum)?;
89 let duration = start.elapsed();
90
91 println!(
92 "Processed {} states in {:?} (multi-threaded mode)",
93 large_states.len(),
94 duration
95 );
96 println!("Results: {} processed states", results.len());
97 println!();
98
99 // Example 5: Custom thread pool with different configurations
100 println!("5. Custom Thread Pool with Different Configurations");
101 println!("===================================================");
102
103 // Security-optimized pool
104 let security_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
105 let security_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
106 let start = Instant::now();
107
108 let _security_results =
109 security_pool.process_keccak_states(&security_states, OptimizationLevel::Reference)?;
110 let security_duration = start.elapsed();
111
112 println!(
113 "Security pool: {} states in {:?} (single-threaded)",
114 security_states.len(),
115 security_duration
116 );
117
118 // Performance-optimized pool
119 let performance_pool = CryptoThreadPool::new(ThreadingConfig::performance_optimized());
120 let performance_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
121 let start = Instant::now();
122
123 let _performance_results = performance_pool
124 .process_keccak_states(&performance_states, OptimizationLevel::Maximum)?;
125 let performance_duration = start.elapsed();
126
127 println!(
128 "Performance pool: {} states in {:?} (multi-threaded)",
129 performance_states.len(),
130 performance_duration
131 );
132 println!();
133
134 // Example 6: Direct multi-threading function usage
135 println!("6. Direct Multi-threading Function Usage");
136 println!("========================================");
137
138 let direct_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
139 let start = Instant::now();
140
141 let direct_results = p1600_multithreaded(&direct_states, OptimizationLevel::Advanced)?;
142 let direct_duration = start.elapsed();
143
144 println!(
145 "Direct function: {} states in {:?}",
146 direct_states.len(),
147 direct_duration
148 );
149 println!("Results: {} processed states", direct_results.len());
150 println!();
151
152 // Example 7: Performance comparison
153 println!("7. Performance Comparison");
154 println!("=========================");
155
156 let test_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
157
158 // Sequential processing
159 let start = Instant::now();
160 let sequential_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
161 let _sequential_results =
162 sequential_pool.process_keccak_states(&test_states, OptimizationLevel::Reference)?;
163 let sequential_duration = start.elapsed();
164
165 // Multi-threaded processing
166 let start = Instant::now();
167 let _multi_results =
168 process_keccak_states_global(&test_states, OptimizationLevel::Maximum)?;
169 let multi_duration = start.elapsed();
170
171 println!("Sequential: {:?}", sequential_duration);
172 println!("Multi-threaded: {:?}", multi_duration);
173
174 if multi_duration < sequential_duration {
175 let speedup = sequential_duration.as_nanos() as f64 / multi_duration.as_nanos() as f64;
176 println!("Speedup: {:.2}x", speedup);
177 } else {
178 println!("Sequential processing was faster (likely due to overhead)");
179 }
180 println!();
181
182 // Example 8: Error handling and graceful degradation
183 println!("8. Error Handling and Graceful Degradation");
184 println!("===========================================");
185
186 // Test with invalid configuration (should fall back to sequential)
187 let invalid_config = ThreadingConfig {
188 num_threads: 0, // Invalid: no threads
189 min_work_size: 100,
190 max_work_per_thread: 1000,
191 timeout: std::time::Duration::from_secs(5),
192 enable_affinity: false,
193 affinity_strategy: lib_q_keccak::AffinityStrategy::Disabled,
194 };
195
196 let fallback_pool = CryptoThreadPool::new(invalid_config);
197 let fallback_states: Vec<[u64; 25]> = vec![[0u64; 25]; 100];
198 let start = Instant::now();
199
200 match fallback_pool.process_keccak_states(&fallback_states, OptimizationLevel::Reference) {
201 Ok(results) => {
202 let duration = start.elapsed();
203 println!(
204 "Fallback successful: {} states in {:?} (sequential fallback)",
205 fallback_states.len(),
206 duration
207 );
208 println!("Results: {} processed states", results.len());
209 }
210 Err(e) => {
211 println!("Fallback failed: {}", e);
212 }
213 }
214 println!();
215
216 println!("=== Multi-threading Example Complete ===");
217 println!("All operations completed successfully!");
218 }
219
220 #[cfg(not(feature = "multithreading"))]
221 {
222 println!("Multi-threading feature not enabled.");
223 println!("Enable with: cargo run --example multithreading_usage --features multithreading");
224 println!();
225 println!("This example demonstrates:");
226 println!("- Thread-safe cryptographic operations");
227 println!("- Configurable thread pools for different use cases");
228 println!("- Performance vs. security trade-offs");
229 println!("- Graceful fallback to sequential processing");
230 println!("- Error handling and timeout management");
231 }
232
233 Ok(())
234}Sourcepub fn balanced() -> Self
pub fn balanced() -> Self
Create a balanced configuration
Examples found in repository?
examples/multithreading_usage.rs (line 48)
21fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
22 #[cfg(feature = "multithreading")]
23 {
24 println!("=== lib-Q Multi-threading Example ===\n");
25
26 // Example 1: Basic multi-threading configuration
27 println!("1. Basic Multi-threading Configuration");
28 println!("=====================================");
29
30 let config = ThreadingConfig::default();
31 println!(
32 "Default config: {} threads, min work size: {} bytes",
33 config.num_threads, config.min_work_size
34 );
35
36 let security_config = ThreadingConfig::security_optimized();
37 println!(
38 "Security config: {} threads (single-threaded for maximum security)",
39 security_config.num_threads
40 );
41
42 let performance_config = ThreadingConfig::performance_optimized();
43 println!(
44 "Performance config: {} threads, min work size: {} bytes",
45 performance_config.num_threads, performance_config.min_work_size
46 );
47
48 let balanced_config = ThreadingConfig::balanced();
49 println!(
50 "Balanced config: {} threads, min work size: {} bytes",
51 balanced_config.num_threads, balanced_config.min_work_size
52 );
53 println!();
54
55 // Example 2: Initialize global thread pool
56 println!("2. Global Thread Pool Initialization");
57 println!("====================================");
58
59 init_global_thread_pool(balanced_config.clone());
60 println!("Global thread pool initialized with balanced configuration");
61 println!();
62
63 // Example 3: Process small workload (sequential fallback)
64 println!("3. Small Workload Processing (Sequential Fallback)");
65 println!("==================================================");
66
67 let small_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10]; // Small workload
68 let start = Instant::now();
69
70 let results = process_keccak_states_global(&small_states, OptimizationLevel::Reference)?;
71 let duration = start.elapsed();
72
73 println!(
74 "Processed {} states in {:?} (sequential mode due to small workload)",
75 small_states.len(),
76 duration
77 );
78 println!("Results: {} processed states", results.len());
79 println!();
80
81 // Example 4: Process large workload (multi-threaded)
82 println!("4. Large Workload Processing (Multi-threaded)");
83 println!("=============================================");
84
85 let large_states: Vec<[u64; 25]> = vec![[0u64; 25]; 10000]; // Large workload
86 let start = Instant::now();
87
88 let results = process_keccak_states_global(&large_states, OptimizationLevel::Maximum)?;
89 let duration = start.elapsed();
90
91 println!(
92 "Processed {} states in {:?} (multi-threaded mode)",
93 large_states.len(),
94 duration
95 );
96 println!("Results: {} processed states", results.len());
97 println!();
98
99 // Example 5: Custom thread pool with different configurations
100 println!("5. Custom Thread Pool with Different Configurations");
101 println!("===================================================");
102
103 // Security-optimized pool
104 let security_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
105 let security_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
106 let start = Instant::now();
107
108 let _security_results =
109 security_pool.process_keccak_states(&security_states, OptimizationLevel::Reference)?;
110 let security_duration = start.elapsed();
111
112 println!(
113 "Security pool: {} states in {:?} (single-threaded)",
114 security_states.len(),
115 security_duration
116 );
117
118 // Performance-optimized pool
119 let performance_pool = CryptoThreadPool::new(ThreadingConfig::performance_optimized());
120 let performance_states: Vec<[u64; 25]> = vec![[0u64; 25]; 1000];
121 let start = Instant::now();
122
123 let _performance_results = performance_pool
124 .process_keccak_states(&performance_states, OptimizationLevel::Maximum)?;
125 let performance_duration = start.elapsed();
126
127 println!(
128 "Performance pool: {} states in {:?} (multi-threaded)",
129 performance_states.len(),
130 performance_duration
131 );
132 println!();
133
134 // Example 6: Direct multi-threading function usage
135 println!("6. Direct Multi-threading Function Usage");
136 println!("========================================");
137
138 let direct_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
139 let start = Instant::now();
140
141 let direct_results = p1600_multithreaded(&direct_states, OptimizationLevel::Advanced)?;
142 let direct_duration = start.elapsed();
143
144 println!(
145 "Direct function: {} states in {:?}",
146 direct_states.len(),
147 direct_duration
148 );
149 println!("Results: {} processed states", direct_results.len());
150 println!();
151
152 // Example 7: Performance comparison
153 println!("7. Performance Comparison");
154 println!("=========================");
155
156 let test_states: Vec<[u64; 25]> = vec![[0u64; 25]; 5000];
157
158 // Sequential processing
159 let start = Instant::now();
160 let sequential_pool = CryptoThreadPool::new(ThreadingConfig::security_optimized());
161 let _sequential_results =
162 sequential_pool.process_keccak_states(&test_states, OptimizationLevel::Reference)?;
163 let sequential_duration = start.elapsed();
164
165 // Multi-threaded processing
166 let start = Instant::now();
167 let _multi_results =
168 process_keccak_states_global(&test_states, OptimizationLevel::Maximum)?;
169 let multi_duration = start.elapsed();
170
171 println!("Sequential: {:?}", sequential_duration);
172 println!("Multi-threaded: {:?}", multi_duration);
173
174 if multi_duration < sequential_duration {
175 let speedup = sequential_duration.as_nanos() as f64 / multi_duration.as_nanos() as f64;
176 println!("Speedup: {:.2}x", speedup);
177 } else {
178 println!("Sequential processing was faster (likely due to overhead)");
179 }
180 println!();
181
182 // Example 8: Error handling and graceful degradation
183 println!("8. Error Handling and Graceful Degradation");
184 println!("===========================================");
185
186 // Test with invalid configuration (should fall back to sequential)
187 let invalid_config = ThreadingConfig {
188 num_threads: 0, // Invalid: no threads
189 min_work_size: 100,
190 max_work_per_thread: 1000,
191 timeout: std::time::Duration::from_secs(5),
192 enable_affinity: false,
193 affinity_strategy: lib_q_keccak::AffinityStrategy::Disabled,
194 };
195
196 let fallback_pool = CryptoThreadPool::new(invalid_config);
197 let fallback_states: Vec<[u64; 25]> = vec![[0u64; 25]; 100];
198 let start = Instant::now();
199
200 match fallback_pool.process_keccak_states(&fallback_states, OptimizationLevel::Reference) {
201 Ok(results) => {
202 let duration = start.elapsed();
203 println!(
204 "Fallback successful: {} states in {:?} (sequential fallback)",
205 fallback_states.len(),
206 duration
207 );
208 println!("Results: {} processed states", results.len());
209 }
210 Err(e) => {
211 println!("Fallback failed: {}", e);
212 }
213 }
214 println!();
215
216 println!("=== Multi-threading Example Complete ===");
217 println!("All operations completed successfully!");
218 }
219
220 #[cfg(not(feature = "multithreading"))]
221 {
222 println!("Multi-threading feature not enabled.");
223 println!("Enable with: cargo run --example multithreading_usage --features multithreading");
224 println!();
225 println!("This example demonstrates:");
226 println!("- Thread-safe cryptographic operations");
227 println!("- Configurable thread pools for different use cases");
228 println!("- Performance vs. security trade-offs");
229 println!("- Graceful fallback to sequential processing");
230 println!("- Error handling and timeout management");
231 }
232
233 Ok(())
234}Trait Implementations§
Source§impl Clone for ThreadingConfig
impl Clone for ThreadingConfig
Source§fn clone(&self) -> ThreadingConfig
fn clone(&self) -> ThreadingConfig
Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for ThreadingConfig
impl Debug for ThreadingConfig
Auto Trait Implementations§
impl Freeze for ThreadingConfig
impl RefUnwindSafe for ThreadingConfig
impl Send for ThreadingConfig
impl Sync for ThreadingConfig
impl Unpin for ThreadingConfig
impl UnsafeUnpin for ThreadingConfig
impl UnwindSafe for ThreadingConfig
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more