thread_share/
macros.rs

1//! # Macros Module
2//!
3//! This module provides convenient macros for creating and managing thread-safe
4//! data structures with minimal boilerplate code.
5//!
6//! ## ๐Ÿš€ Overview
7//!
8//! The macros module contains several utility macros that simplify common
9//! operations when working with ThreadShare structures:
10//!
11//! - **`share!`** - Creates `ThreadShare<T>` instances with automatic type inference
12//! - **`simple_share!`** - Creates `SimpleShare<T>` instances for basic use cases
13//! - **`enhanced_share!`** - Creates `EnhancedThreadShare<T>` instances
14//! - **`spawn_workers!`** - Spawns multiple threads with single macro call, returns WorkerManager
15//! - **`spawn_threads!`** - Alternative thread spawning macro for ThreadManager
16//! - **`thread_setup!`** - Sets up thread management with shared data, returns ThreadManager
17//!
18//! ## Key Benefits
19//!
20//! ### ๐ŸŽฏ Simplified Creation
21//! ```rust
22//! use thread_share::{share, ThreadShare};
23//!
24//! // Without macros
25//! let counter = ThreadShare::new(0);
26//! let message = ThreadShare::new(String::from("Hello"));
27//! let data = ThreadShare::new(vec![1, 2, 3]);
28//!
29//! // With macros
30//! let counter = share!(0);
31//! let message = share!(String::from("Hello"));
32//! let data = share!(vec![1, 2, 3]);
33//! ```
34//!
35//! ### ๐Ÿงต Enhanced Thread Management
36//! ```rust
37//! use thread_share::{enhanced_share, spawn_workers};
38//!
39//! let data = enhanced_share!(vec![1, 2, 3]);
40//!
41//! // Single macro call spawns all threads
42//! spawn_workers!(data, {
43//!     processor: |data| { data.update(|v| v.sort()); },
44//!     validator: |data| { assert!(data.get().is_sorted()); }
45//! });
46//!
47//! data.join_all().expect("Failed to join");
48//! ```
49//!
50//! ## Macro Reference
51//!
52//! ### share! Macro
53//!
54//! Creates a `ThreadShare<T>` instance with automatic type inference.
55//!
56//! **Syntax**: `share!(expression)`
57//!
58//! **Example**:
59//! ```rust
60//! use thread_share::share;
61//!
62//! let counter = share!(0);                    // ThreadShare<i32>
63//! let message = share!("Hello");              // ThreadShare<&str>
64//! let data = share!(vec![1, 2, 3]);          // ThreadShare<Vec<i32>>
65//! // let user = share!(User { id: 1, name: "Alice" }); // ThreadShare<User>
66//! ```
67//!
68//! ### simple_share! Macro
69//!
70//! Creates a `SimpleShare<T>` instance for basic data sharing without change detection.
71//!
72//! **Syntax**: `simple_share!(expression)`
73//!
74//! **Example**:
75//! ```rust
76//! use thread_share::simple_share;
77//!
78//! let counter = simple_share!(0);             // SimpleShare<i32>
79//! let flag = simple_share!(false);            // SimpleShare<bool>
80//! let data = simple_share!(String::new());    // SimpleShare<String>
81//! ```
82//!
83//! ### enhanced_share! Macro
84//!
85//! Creates an `EnhancedThreadShare<T>` instance with automatic thread management.
86//!
87//! **Syntax**: `enhanced_share!(expression)`
88//!
89//! **Example**:
90//! ```rust
91//! use thread_share::enhanced_share;
92//!
93//! let data = enhanced_share!(vec![1, 2, 3]);
94//!
95//! // Now you can use enhanced thread management
96//! data.spawn("worker", |data| {
97//!     data.update(|v| v.push(4));
98//! });
99//!
100//! data.join_all().expect("Failed to join");
101//! ```
102//!
103//! ### spawn_workers! Macro
104//!
105//! Spawns multiple threads with a single macro call, each with a descriptive name.
106//!
107//! **Syntax**: `spawn_workers!(data, { name: closure, ... })`
108//!
109//! **Example**:
110//! ```rust
111//! use thread_share::{enhanced_share, spawn_workers};
112//!
113//! let data = enhanced_share!(0);
114//!
115//! spawn_workers!(data, {
116//!     incrementer: |data| {
117//!         for _ in 0..100 {
118//!             data.update(|x| *x += 1);
119//!         }
120//!     },
121//!     monitor: |data| {
122//!         for _ in 0..10 {
123//!             std::thread::sleep(std::time::Duration::from_millis(100));
124//!             println!("Value: {}", data.get());
125//!         }
126//!     }
127//! });
128//!
129//! data.join_all().expect("Failed to join");
130//! ```
131//!
132//! ### spawn_threads! Macro
133//!
134//! Alternative macro for spawning threads with different syntax.
135//!
136//! **Syntax**: `spawn_threads!(data, [closure1, closure2, ...])`
137//!
138//! **Example**:
139//! ```rust
140//! use thread_share::{enhanced_share, spawn_workers};
141//!
142//! let data = enhanced_share!(String::from("Hello"));
143//!
144//! spawn_workers!(data, {
145//!     worker1: |data| { data.update(|s| s.push_str(" World")); },
146//!     worker2: |data| { data.update(|s| s.push_str("!")); }
147//! });
148//!
149//! data.join_all().expect("Failed to join");
150//! ```
151//!
152//! ### thread_setup! Macro
153//!
154//! Sets up thread management with shared data and multiple worker functions.
155//!
156//! **Syntax**: `thread_setup!(shared_data, { name: function, ... })`
157//!
158//! **Example**:
159//! ```rust
160//! use thread_share::{share, thread_setup};
161//!
162//! let shared_data = share!(vec![1, 2, 3]);
163//!
164//! let manager = thread_setup!(shared_data, {
165//!     worker1: |data| { data.update(|v| v.push(4)); },
166//!     worker2: |data| { data.update(|v| v.push(5)); }
167//! });
168//!
169//! manager.join_all().expect("Failed to join");
170//! ```
171//!
172//! ## Type Inference
173//!
174//! All macros provide automatic type inference, so you don't need to specify
175//! generic types explicitly:
176//!
177//! ```rust
178//! use thread_share::share;
179//!
180//! // Type is automatically inferred as ThreadShare<i32>
181//! let counter = share!(0);
182//!
183//! // Type is automatically inferred as ThreadShare<Vec<String>>
184//! let data = share!(vec![String::from("a"), String::from("b")]);
185//!
186//! // Type is automatically inferred as ThreadShare<Option<bool>>
187//! let flag = share!(Some(true));
188//! ```
189//!
190//! ## Error Handling
191//!
192//! Basic error handling with standard threads:
193//!
194//! ```rust
195//! use thread_share::share;
196//!
197//! let data = share!(0);
198//! let clone = data.clone();
199//!
200//! // Spawn thread with error handling
201//! let handle = std::thread::spawn(move || {
202//!     clone.update(|x| *x = *x + 1);
203//! });
204//!
205//! // Handle join errors
206//! if let Err(e) = handle.join() {
207//!     eprintln!("Thread execution failed: {:?}", e);
208//! }
209//! ```
210//!
211//! ## Best Practices
212//!
213//! 1. **Use descriptive names** for spawned threads to aid debugging
214//! 2. **Keep closures focused** on single responsibilities
215//! 3. **Handle errors gracefully** from thread spawning and joining
216//! 4. **Prefer `spawn_workers!`** over manual thread management
217//! 5. **Use `enhanced_share!`** when you need automatic thread management
218//!
219//! ## Performance Considerations
220//!
221//! - **Macro expansion**: Happens at compile time, no runtime overhead
222//! - **Type inference**: Compiler optimizations apply normally
223//! - **Thread spawning**: Same performance as manual `thread::spawn`
224//! - **Memory usage**: No additional overhead from macro usage
225//!
226//! ## Integration with Other Modules
227//!
228//! ```
229
230/// Macro for creating ThreadShare with automatic type inference
231///
232/// This macro creates a `ThreadShare<T>` instance with automatic type inference.
233/// It's the most commonly used macro for creating thread-safe shared data.
234///
235/// ## Syntax
236///
237/// `share!(expression)`
238///
239/// ## Arguments
240///
241/// * `expression` - The data to wrap in ThreadShare
242///
243/// ## Returns
244///
245/// A new `ThreadShare<T>` instance where `T` is inferred from the expression.
246///
247/// ## Example
248///
249/// ```rust
250/// use thread_share::share;
251///
252/// // Basic types
253/// let counter = share!(0);                    // ThreadShare<i32>
254/// let message = share!("Hello");              // ThreadShare<&str>
255/// let flag = share!(true);                    // ThreadShare<bool>
256///
257/// // Complex types
258/// let data = share!(vec![1, 2, 3]);          // ThreadShare<Vec<i32>>
259/// // let user = share!(User { id: 1, name: "Alice" }); // ThreadShare<User>
260///
261/// // Expressions
262/// let result = share!(10 + 20);               // ThreadShare<i32>
263/// let computed = share!(vec![1, 2, 3].len()); // ThreadShare<usize>
264/// ```
265///
266/// ## Type Inference
267///
268/// The macro automatically infers the generic type `T` from the expression:
269///
270/// ```rust
271/// use thread_share::share;
272///
273/// // No need to specify types explicitly
274/// let counter: thread_share::ThreadShare<i32> = share!(0);
275/// let data: thread_share::ThreadShare<Vec<String>> = share!(vec![String::new()]);
276/// ```
277#[macro_export]
278macro_rules! share {
279    ($data:expr) => {
280        $crate::ThreadShare::new($data)
281    };
282}
283
284/// Macro for creating SimpleShare
285///
286/// This macro creates a `SimpleShare<T>` instance for basic data sharing
287/// without change detection capabilities.
288///
289/// ## Syntax
290///
291/// `simple_share!(expression)`
292///
293/// ## Arguments
294///
295/// * `expression` - The data to wrap in SimpleShare
296///
297/// ## Returns
298///
299/// A new `SimpleShare<T>` instance where `T` is inferred from the expression.
300///
301/// ## Example
302///
303/// ```rust
304/// use thread_share::simple_share;
305///
306/// // Basic types
307/// let counter = simple_share!(0);             // SimpleShare<i32>
308/// let message = simple_share!("Hello");       // SimpleShare<&str>
309/// let flag = simple_share!(false);            // SimpleShare<bool>
310///
311/// // Complex types
312/// let data = simple_share!(vec![1, 2, 3]);   // SimpleShare<Vec<i32>>
313/// // let user = simple_share!(User { id: 1, name: "Bob" }); // SimpleShare<User>
314/// ```
315///
316/// ## When to Use
317///
318/// Use `simple_share!` when you need:
319/// - Basic data sharing without change detection
320/// - Minimal overhead and complexity
321/// - Simple producer-consumer patterns
322/// - Learning and prototyping
323///
324/// Use `share!` when you need:
325/// - Change detection and waiting mechanisms
326/// - Complex synchronization patterns
327/// - Maximum flexibility and features
328#[macro_export]
329macro_rules! simple_share {
330    ($data:expr) => {
331        $crate::SimpleShare::new($data)
332    };
333}
334
335/// Macro for creating enhanced thread share with automatic thread management
336///
337/// This macro creates an `EnhancedThreadShare<T>` instance that provides
338/// automatic thread management capabilities.
339///
340/// ## Syntax
341///
342/// `enhanced_share!(expression)`
343///
344/// ## Arguments
345///
346/// * `expression` - The data to wrap in EnhancedThreadShare
347///
348/// ## Returns
349///
350/// A new `EnhancedThreadShare<T>` instance where `T` is inferred from the expression.
351///
352/// ## Example
353///
354/// ```rust
355/// use thread_share::enhanced_share;
356///
357/// // Basic types
358/// let counter = enhanced_share!(0);                    // EnhancedThreadShare<i32>
359/// let message = enhanced_share!(String::from("Hello")); // EnhancedThreadShare<String>
360/// let data = enhanced_share!(vec![1, 2, 3]);          // EnhancedThreadShare<Vec<i32>>
361/// ```
362///
363/// ## Key Features
364///
365/// - **Automatic Thread Management**: Spawn threads with a single method call
366/// - **Built-in Thread Tracking**: Monitor active thread count and status
367/// - **Automatic Thread Joining**: Wait for all threads to complete with `join_all()`
368/// - **Thread Naming**: Give meaningful names to threads for debugging
369/// - **All ThreadShare Features**: Inherits all capabilities from `ThreadShare<T>`
370///
371/// ## When to Use
372///
373/// Use `enhanced_share!` when you need:
374/// - Complex multi-threaded applications
375/// - Automatic thread lifecycle management
376/// - Thread monitoring and debugging
377/// - High-level thread coordination
378///
379/// Use `share!` when you need:
380/// - Simple data sharing without thread management
381/// - Manual thread control
382/// - Minimal overhead
383#[macro_export]
384macro_rules! enhanced_share {
385    ($data:expr) => {
386        $crate::enhanced::EnhancedThreadShare::new($data)
387    };
388}
389
390/// Macro for simplified multi-threaded setup with WorkerManager
391///
392/// This macro spawns multiple threads and returns a `WorkerManager` instance
393/// that allows you to control individual workers: pause, resume, stop, and monitor them.
394///
395/// ## Syntax
396///
397/// `spawn_workers!(shared_data, { name: closure, ... })`
398///
399/// ## Arguments
400///
401/// * `shared_data` - An `EnhancedThreadShare<T>` instance to share between workers
402/// * `{ name: closure, ... }` - Named closures for each worker thread
403///
404/// ## Returns
405///
406/// A `WorkerManager` instance that provides methods to control workers:
407/// - `add_worker(name, handle)` - Add a new worker programmatically
408/// - `pause_worker(name)` - Mark a worker for pause
409/// - `resume_worker(name)` - Resume a paused worker
410/// - `remove_worker(name)` - Remove worker from tracking
411/// - `get_worker_names()` - Get list of all worker names
412/// - `active_workers()` - Get count of active workers
413/// - `join_all()` - Wait for all workers to complete
414///
415/// ## Example
416///
417/// ```rust
418/// use thread_share::{enhanced_share, spawn_workers};
419///
420/// let data = enhanced_share!(vec![1, 2, 3]);
421///
422/// // Spawn workers and get manager
423/// let manager = spawn_workers!(data, {
424///     sorter: |data| {
425///         data.update(|v| v.sort());
426///     },
427///     validator: |data| {
428///         assert!(data.get().is_sorted());
429///     }
430/// });
431///
432/// // Control workers
433/// println!("Workers: {:?}", manager.get_worker_names());
434/// println!("Active: {}", manager.active_workers());
435///
436/// // Wait for completion
437/// manager.join_all().expect("Workers failed");
438/// ```
439///
440/// ## Worker Management
441///
442/// The `WorkerManager` allows fine-grained control over individual workers:
443///
444/// ```rust
445/// use thread_share::{enhanced_share, spawn_workers};
446///
447/// let data = enhanced_share!(vec![1, 2, 3]);
448/// let manager = spawn_workers!(data, {
449///     sorter: |data| { /* work */ },
450///     validator: |data| { /* work */ }
451/// });
452///
453/// // Pause a specific worker
454/// let _ = manager.pause_worker("sorter");
455///
456/// // Resume a worker
457/// let _ = manager.resume_worker("sorter");
458///
459/// // Add a new worker programmatically
460/// let handle = std::thread::spawn(|| { /* work */ });
461/// let _ = manager.add_worker("new_worker", handle);
462///
463/// // Remove from tracking
464/// let _ = manager.remove_worker("sorter");
465/// ```
466///
467/// ## Requirements
468///
469/// - The shared data must be an `EnhancedThreadShare<T>` instance
470/// - Each closure must implement `FnOnce(ThreadShare<T>) + Send + 'static`
471/// - The type `T` must implement `Send + Sync + 'static`
472///
473/// ## Performance
474///
475/// - **Thread Spawning**: Minimal overhead over standard `thread::spawn`
476/// - **Worker Management**: Constant-time operations for most management functions
477/// - **Memory Usage**: Small overhead for worker tracking structures
478/// - **Scalability**: Efficient for up to hundreds of workers
479#[macro_export]
480macro_rules! spawn_workers {
481    ($shared:expr, { $($name:ident: $func:expr),* }) => {
482        {
483            $(
484                $shared.spawn(stringify!($name), $func).expect(&format!("Failed to spawn {}", stringify!($name)));
485            )*
486            $crate::worker_manager::WorkerManager::new_with_threads($shared.get_threads())
487        }
488    };
489}
490
491/// Macro for simplified thread spawning
492///
493/// This macro simplifies spawning multiple threads with the same shared data.
494/// It creates a vector of thread configurations and calls `spawn_multiple`.
495///
496/// ## Syntax
497///
498/// `spawn_threads!(manager, shared_data, { name: function, ... })`
499///
500/// ## Arguments
501///
502/// * `manager` - The ThreadManager instance
503/// * `shared_data` - The ThreadShare<T> data to share
504/// * `{ name: function, ... }` - Named thread functions
505///
506/// ## Returns
507///
508/// `Result<(), String>` from `spawn_multiple`.
509///
510/// ## Performance
511///
512/// - **Compile-time expansion**: No runtime overhead
513/// - **Efficient spawning**: Same performance as manual `spawn_multiple`
514/// - **Type safety**: Compile-time type checking
515/// - **Memory usage**: No additional allocations
516#[macro_export]
517macro_rules! spawn_threads {
518    ($manager:expr, $shared_data:expr, { $($name:ident: $func:expr),* }) => {
519        {
520            let configs = vec![
521                $(
522                    (stringify!($name), $func)
523                ),*
524            ];
525            $manager.spawn_multiple($shared_data, configs)
526        }
527    };
528}
529
530/// Macro for creating a complete thread setup
531///
532/// This macro creates a ThreadManager and spawns multiple threads with shared data
533/// in a single call, returning the manager for further control.
534///
535/// ## Syntax
536///
537/// `thread_setup!(shared_data, { name: function, ... })`
538///
539/// ## Arguments
540///
541/// * `shared_data` - The ThreadShare<T> data to share
542/// * `{ name: function, ... }` - Named thread functions
543///
544/// ## Returns
545///
546/// A `ThreadManager` instance that can be used to control the spawned threads.
547///
548/// ## Example
549///
550/// ```rust
551/// use thread_share::{share, thread_setup};
552///
553/// let data = share!(0);
554///
555/// let manager = thread_setup!(data, {
556///     counter: |data| { data.update(|x| *x += 1); },
557///     monitor: |data| { println!("Value: {}", data.get()); }
558/// });
559///
560/// // Wait for all threads
561/// manager.join_all().expect("Failed to join threads");
562/// ```
563#[macro_export]
564macro_rules! thread_setup {
565    ($shared_data:expr, { $($name:ident: $func:expr),* }) => {
566        {
567            let manager = $crate::thread_pool::ThreadManager::new();
568            $(
569                manager.spawn(stringify!($name), $shared_data.clone(), $func)
570                    .expect(&format!("Failed to spawn {}", stringify!($name)));
571            )*
572            manager
573        }
574    };
575}