thread_share/
lib.rs

1//! # Thread-Share
2//!
3//! A comprehensive Rust library for safe and efficient data exchange between threads.
4//!
5//! ## ๐Ÿš€ Features
6//!
7//! - **Simple API** for data exchange between threads
8//! - **Automatic synchronization** and thread safety
9//! - **Support for any data types** that implement `Clone`
10//! - **Efficient synchronization** using `parking_lot`
11//! - **Multiple complexity levels**: from simple locks to zero-copy atomic operations
12//! - **Enhanced thread management** with automatic spawning and joining
13//! - **Smart macros** for cleaner thread management syntax
14//! - **Real-world examples** including HTTP server and socket client
15//!
16//! ## ๐ŸŽฏ Quick Start
17//!
18//! ```rust
19//! use thread_share::share;
20//!
21//! // Create shared data
22//! let counter = share!(0);
23//! let clone = counter.clone();
24//!
25//! // Spawn a simple thread
26//! std::thread::spawn(move || {
27//!     clone.update(|x| *x = *x + 1);
28//! });
29//!
30//! // Wait a bit and check result
31//! std::thread::sleep(std::time::Duration::from_millis(100));
32//! println!("Final value: {}", counter.get());
33//! ```
34//!
35//! ## ๐Ÿ—๏ธ Architecture Overview
36//!
37//! The library provides several levels of abstraction:
38//!
39//! ### ๐Ÿ”’ Lock-Based (Safe & Predictable)
40//! - **`ThreadShare<T>`** - Full-featured synchronization with change detection
41//! - **`SimpleShare<T>`** - Lightweight alternative for basic use cases
42//! - **`ArcThreadShareLocked<T>`** - Safe zero-copy with read/write locks
43//!
44//! ### โšก Atomic-Based (High Performance)
45//! - **`ArcThreadShare<T>`** - Zero-copy atomic operations (use with caution)
46//!
47//! ### ๐Ÿงต Enhanced Management
48//! - **`EnhancedThreadShare<T>`** - Automatic thread spawning and joining
49//! - **`ThreadManager`** - Standalone thread management utility
50//!
51//! ## ๐Ÿ“š Core Concepts
52//!
53//! ### ThreadShare<T> - Main Structure
54//! Provides comprehensive thread synchronization with automatic cloning:
55//!
56//! ```rust
57//! use thread_share::share;
58//!
59//! let data = share!(vec![1, 2, 3]);
60//! let clone = data.clone();
61//!
62//! // Thread 1
63//! std::thread::spawn(move || {
64//!     clone.update(|v| v.push(4));
65//! });
66//!
67//! // Thread 2 (main)
68//! data.wait_for_change_forever();
69//! println!("Updated: {:?}", data.get());
70//! ```
71//!
72//! ### ThreadShare<T> - Basic Management
73//! Simple thread management with manual control:
74//!
75//! ```rust
76//! use thread_share::share;
77//!
78//! let data = share!(vec![1, 2, 3]);
79//! let clone = data.clone();
80//!
81//! std::thread::spawn(move || {
82//!     clone.update(|d| d.push(4));
83//! });
84//!
85//! std::thread::sleep(std::time::Duration::from_millis(100));
86//! println!("Updated: {:?}", data.get());
87//! ```
88//!
89//! ## ๐Ÿ”ง Usage Patterns
90//!
91//! ### Serialization Support (Optional Feature)
92//!
93//! The library provides optional serialization support through the `serialize` feature:
94//!
95//! ```bash
96//! # Enable serialization support
97//! cargo add thread-share --features serialize
98//! ```
99//!
100//! ```rust
101//! use thread_share::ThreadShare;
102//!
103//! // Note: This example requires the 'serialize' feature
104//! let data = ThreadShare::new(vec![1, 2, 3]);
105//!
106//! // Serialize to JSON (available with serialize feature)
107//! // let json = data.to_json().expect("Failed to serialize");
108//! // println!("JSON: {}", json); // Output: [1,2,3]
109//!
110//! // Deserialize from JSON (available with serialize feature)
111//! // data.from_json("[4,5,6]").expect("Failed to deserialize");
112//! // assert_eq!(data.get(), vec![4, 5, 6]);
113//! ```
114//!
115//! **Note**: Serialization methods are only available when the `serialize` feature is enabled.
116//!
117//! ### Basic Data Sharing
118//! ```rust
119//! use thread_share::share;
120//!
121//! let counter = share!(0);
122//! let clone = counter.clone();
123//!
124//! std::thread::spawn(move || {
125//!     for _ in 0..100 {
126//!         clone.update(|x| *x += 1);
127//!     }
128//! });
129//!
130//! std::thread::sleep(std::time::Duration::from_millis(100));
131//! println!("Counter: {}", counter.get());
132//! ```
133//!
134//! ### Zero-Copy Operations
135//! ```rust
136//! use thread_share::{share, ArcThreadShare};
137//!
138//! let data = share!(String::from("Hello"));
139//! let arc_data = data.as_arc();
140//! let arc_share = ArcThreadShare::from_arc(arc_data);
141//!
142//! // Use atomic operations for performance
143//! arc_share.update(|s| s.push_str(" World"));
144//! ```
145//!
146//! ### Enhanced Thread Management
147//! ```rust
148//! use thread_share::{enhanced_share, spawn_workers};
149//!
150//! let data = enhanced_share!(vec![1, 2, 3]);
151//!
152//! spawn_workers!(data, {
153//!     processor: |data| { data.update(|v| v.sort()); },
154//!     validator: |data| { assert!(data.get().is_sorted()); }
155//! });
156//!
157//! data.join_all().expect("Failed to join");
158//! ```
159//!
160//! ## โš ๏ธ Important Notes
161//!
162//! ### ArcThreadShare Limitations
163//! - **Complex operations are not atomic** - use `increment()` and `add()` methods
164//! - **High contention can cause lost updates** - test with realistic load
165//! - **Memory allocation overhead** per operation
166//!
167//! ### Best Practices
168//! - Use **`ThreadShare<T>`** for most applications
169//! - Use **`ArcThreadShare<T>`** only when you understand its limitations
170//! - Use **`EnhancedThreadShare<T>`** for simplified thread management
171//! - Always test with realistic contention levels
172//!
173//! ## ๐Ÿ“– Examples
174//!
175//! Check the `examples/` directory for complete working examples:
176//!
177//! - **`basic_usage.rs`** - Fundamental concepts
178//! - **`http_integration_helpers.rs`** - Complete HTTP server
179//! - **`socket_client_usage.rs`** - Enhanced socket client
180//! - **`atomic_usage.rs`** - Zero-copy patterns
181//!
182//! ## ๐Ÿงช Testing
183//!
184//! Run the comprehensive test suite:
185//!
186//! ```bash
187//! cargo test                    # All tests
188//! cargo test --test core_tests # Specific test file
189//! cargo test -- --nocapture    # With output
190//! ```
191//!
192//! ## ๐Ÿ“„ License
193//!
194//! This project is licensed under the MIT License.
195//!
196//! ## ๐Ÿค Contributing
197//!
198//! Contributions are welcome! Please feel free to submit a Pull Request.
199
200pub mod atomic;
201pub mod core;
202pub mod enhanced;
203pub mod locked;
204pub mod macros;
205pub mod thread_pool;
206pub mod worker_manager;
207
208// Re-export main structures
209pub use atomic::ArcThreadShare;
210pub use core::{SimpleShare, ThreadShare};
211pub use enhanced::EnhancedThreadShare;
212pub use locked::ArcThreadShareLocked;
213pub use thread_pool::ThreadManager;
214
215