thread_share/core.rs
1//! # Core Module - ThreadShare and SimpleShare
2//!
3//! This module provides the core structures for safe data exchange between threads.
4//!
5//! ## Overview
6//!
7//! The core module contains two main structures:
8//!
9//! - **`ThreadShare<T>`** - Full-featured synchronization with change detection
10//! - **`SimpleShare<T>`** - Lightweight alternative for basic use cases
11//!
12//! ## ThreadShare<T>
13//!
14//! `ThreadShare<T>` is the main structure that provides comprehensive thread synchronization.
15//! It uses `Arc<RwLock<T>>` internally and provides automatic change notification.
16//!
17//! ### Key Features
18//!
19//! - **Automatic Cloning**: Each thread gets its own clone for safe access
20//! - **Change Detection**: Built-in waiting mechanisms for data changes
21//! - **Flexible Access**: Read, write, and update operations with proper locking
22//! - **Condition Variables**: Efficient waiting for data modifications
23//! - **Thread Safety**: Implements `Send` and `Sync` automatically
24//!
25//! ### Example Usage
26//!
27//! ```rust
28//! use thread_share::ThreadShare;
29//! use std::thread;
30//! use std::time::Duration;
31//!
32//! let data = ThreadShare::new(vec![1, 2, 3]);
33//! let clone = data.clone();
34//!
35//! // Spawn a thread that modifies the data
36//! thread::spawn(move || {
37//! thread::sleep(Duration::from_millis(100));
38//! clone.update(|v| v.push(4));
39//! });
40//!
41//! // Wait for changes and read the result
42//! data.wait_for_change_forever();
43//! let result = data.get();
44//! assert_eq!(result, vec![1, 2, 3, 4]);
45//! ```
46//!
47//! ### Performance Characteristics
48//!
49//! - **Read Operations**: Multiple threads can read simultaneously
50//! - **Write Operations**: Exclusive access during writes
51//! - **Change Detection**: Efficient condition variable notifications
52//! - **Memory Overhead**: Minimal overhead from Arc and RwLock structures
53//!
54//! ## SimpleShare<T>
55//!
56//! `SimpleShare<T>` is a simplified version of `ThreadShare<T>` that provides
57//! basic functionality without change detection.
58//!
59//! ### Key Features
60//!
61//! - **Minimal Overhead**: Lighter synchronization primitives
62//! - **Essential Operations**: Basic get/set/update functionality
63//! - **Clone Support**: Each thread gets a clone for safe access
64//! - **No Change Detection**: Simpler implementation without condition variables
65//!
66//! ### Example Usage
67//!
68//! ```rust
69//! use thread_share::SimpleShare;
70//! use std::thread;
71//! use std::time::Duration;
72//!
73//! let counter = SimpleShare::new(0);
74//! let clone = counter.clone();
75//!
76//! thread::spawn(move || {
77//! for _ in 0..100 {
78//! clone.update(|x| *x = *x + 1);
79//! }
80//! });
81//!
82//! thread::sleep(Duration::from_millis(100));
83//! assert_eq!(counter.get(), 100);
84//! ```
85//!
86//! ## When to Use Each
87//!
88//! ### Use ThreadShare<T> when you need:
89//! - Change detection and waiting mechanisms
90//! - Complex synchronization patterns
91//! - Maximum flexibility and features
92//! - Production applications with complex requirements
93//!
94//! ### Use SimpleShare<T> when you need:
95//! - Basic data sharing without change detection
96//! - Minimal overhead and complexity
97//! - Simple producer-consumer patterns
98//! - Learning and prototyping
99//!
100//! ## Thread Safety
101//!
102//! Both structures automatically implement `Send` and `Sync` traits, making them
103//! safe to use across thread boundaries. The internal synchronization primitives
104//! ensure that all operations are thread-safe.
105//!
106//! ## Memory Management
107//!
108//! - **Arc**: Provides reference counting for shared ownership
109//! - **RwLock**: Ensures exclusive write access and concurrent read access
110//! - **Mutex**: Protects condition variable access
111//! - **Condvar**: Enables efficient waiting for changes
112//!
113//! ## Best Practices
114//!
115//! 1. **Always clone for thread usage**: Use `.clone()` to get thread-safe copies
116//! 2. **Use appropriate access patterns**: `read()` for read-only, `write()` for modifications
117//! 3. **Consider change detection**: Use `wait_for_change()` when you need to react to updates
118//! 4. **Minimize lock contention**: Keep critical sections as short as possible
119//! 5. **Handle errors gracefully**: Always check return values from operations
120
121use parking_lot::RwLock;
122use std::sync::{Arc, Condvar, Mutex};
123use std::time::Duration;
124
125#[cfg(feature = "serialize")]
126use serde::{de::DeserializeOwned, Serialize};
127
128// Conditional compilation for serialization support
129#[cfg(feature = "serialize")]
130impl<T> ThreadShare<T>
131where
132 T: Serialize + DeserializeOwned + Clone,
133{
134 /// Serializes the current data to JSON string
135 ///
136 /// This method requires the `serialize` feature to be enabled.
137 ///
138 /// ## Returns
139 ///
140 /// JSON string representation of the data, or error string if serialization fails.
141 ///
142 /// ## Example
143 ///
144 /// ```rust
145 /// use thread_share::ThreadShare;
146 ///
147 /// #[cfg(feature = "serialize")]
148 /// {
149 /// let data = ThreadShare::new(vec![1, 2, 3]);
150 /// let json = data.to_json().expect("Failed to serialize");
151 /// assert_eq!(json, "[1,2,3]");
152 /// }
153 /// ```
154 pub fn to_json(&self) -> Result<String, String> {
155 let data = self.data.read();
156 serde_json::to_string(&*data).map_err(|e| format!("Serialization failed: {}", e))
157 }
158
159 /// Deserializes data from JSON string
160 ///
161 /// This method requires the `serialize` feature to be enabled.
162 ///
163 /// ## Arguments
164 ///
165 /// * `json` - JSON string to deserialize
166 ///
167 /// ## Returns
168 ///
169 /// `Ok(())` on success, `Err(String)` if deserialization fails.
170 ///
171 /// ## Example
172 ///
173 /// ```rust
174 /// use thread_share::ThreadShare;
175 ///
176 /// #[cfg(feature = "serialize")]
177 /// {
178 /// let data = ThreadShare::new(vec![0; 0]);
179 /// data.from_json("[1,2,3]").expect("Failed to deserialize");
180 /// assert_eq!(data.get(), vec![1, 2, 3]);
181 /// }
182 /// ```
183 pub fn from_json(&self, json: &str) -> Result<(), String> {
184 let deserialized: T =
185 serde_json::from_str(json).map_err(|e| format!("Deserialization failed: {}", e))?;
186
187 self.set(deserialized);
188 Ok(())
189 }
190}
191
192/// Main structure for data exchange between threads
193///
194/// `ThreadShare<T>` provides comprehensive thread synchronization with automatic
195/// change detection and efficient locking mechanisms.
196///
197/// ## Features
198///
199/// - **Automatic Cloning**: Each thread gets its own clone for safe access
200/// - **Change Detection**: Built-in waiting mechanisms for data changes
201/// - **Flexible Access**: Read, write, and update operations with proper locking
202/// - **Condition Variables**: Efficient waiting for data modifications
203/// - **Thread Safety**: Implements `Send` and `Sync` automatically
204///
205/// ## Example
206///
207/// ```rust
208/// use thread_share::ThreadShare;
209/// use std::thread;
210///
211/// let data = ThreadShare::new(vec![1, 2, 3]);
212/// let clone = data.clone();
213///
214/// thread::spawn(move || {
215/// clone.update(|v| v.push(4));
216/// });
217///
218/// data.wait_for_change_forever();
219/// assert_eq!(data.get(), vec![1, 2, 3, 4]);
220/// ```
221///
222/// ## Performance
223///
224/// - **Read Operations**: Multiple threads can read simultaneously
225/// - **Write Operations**: Exclusive access during writes
226/// - **Change Detection**: Efficient condition variable notifications
227/// - **Memory Overhead**: Minimal overhead from Arc and RwLock structures
228pub struct ThreadShare<T> {
229 data: Arc<RwLock<T>>,
230 sender: Arc<Mutex<()>>,
231 receiver: Arc<Mutex<()>>,
232 condvar: Arc<Condvar>,
233}
234
235// Automatically implement Send and Sync for ThreadShare
236unsafe impl<T> Send for ThreadShare<T> {}
237unsafe impl<T> Sync for ThreadShare<T> {}
238
239impl<T> ThreadShare<T> {
240 /// Creates a new ThreadShare instance with data
241 ///
242 /// ## Arguments
243 ///
244 /// * `data` - The initial data to share between threads
245 ///
246 /// ## Example
247 ///
248 /// ```rust
249 /// use thread_share::ThreadShare;
250 ///
251 /// let counter = ThreadShare::new(0);
252 /// let data = ThreadShare::new(vec![1, 2, 3]);
253 /// let message = ThreadShare::new(String::from("Hello"));
254 /// ```
255 pub fn new(data: T) -> Self {
256 Self {
257 data: Arc::new(RwLock::new(data)),
258 sender: Arc::new(Mutex::new(())),
259 receiver: Arc::new(Mutex::new(())),
260 condvar: Arc::new(Condvar::new()),
261 }
262 }
263
264 /// Gets a copy of data (for types implementing Clone)
265 ///
266 /// ## Requirements
267 ///
268 /// The type `T` must implement `Clone` trait.
269 ///
270 /// ## Returns
271 ///
272 /// A copy of the current data.
273 ///
274 /// ## Example
275 ///
276 /// ```rust
277 /// use thread_share::ThreadShare;
278 ///
279 /// let counter = ThreadShare::new(42);
280 /// let value = counter.get();
281 /// assert_eq!(value, 42);
282 /// ```
283 pub fn get(&self) -> T
284 where
285 T: Clone,
286 {
287 self.data.read().clone()
288 }
289
290 /// Gets a reference to data for reading
291 ///
292 /// This method provides read-only access to the data through a closure.
293 /// Multiple threads can read simultaneously.
294 ///
295 /// ## Arguments
296 ///
297 /// * `f` - Closure that receives a reference to the data
298 ///
299 /// ## Returns
300 ///
301 /// The result of the closure execution.
302 ///
303 /// ## Example
304 ///
305 /// ```rust
306 /// use thread_share::ThreadShare;
307 ///
308 /// let data = ThreadShare::new(vec![1, 2, 3]);
309 /// let length = data.read(|v| v.len());
310 /// assert_eq!(length, 3);
311 ///
312 /// let sum: i32 = data.read(|v| v.iter().sum());
313 /// assert_eq!(sum, 6);
314 /// ```
315 pub fn read<F, R>(&self, f: F) -> R
316 where
317 F: FnOnce(&T) -> R,
318 {
319 let data = self.data.read();
320 f(&data)
321 }
322
323 /// Gets a mutable reference to data
324 ///
325 /// This method provides mutable access to the data through a closure.
326 /// Only one thread can write at a time.
327 ///
328 /// ## Arguments
329 ///
330 /// * `f` - Closure that receives a mutable reference to the data
331 ///
332 /// ## Returns
333 ///
334 /// The result of the closure execution.
335 ///
336 /// ## Example
337 ///
338 /// ```rust
339 /// use thread_share::ThreadShare;
340 ///
341 /// let data = ThreadShare::new(vec![1, 2, 3]);
342 /// let length = data.write(|v| {
343 /// v.push(4);
344 /// v.len()
345 /// });
346 /// assert_eq!(length, 4);
347 /// assert_eq!(data.get(), vec![1, 2, 3, 4]);
348 /// ```
349 pub fn write<F, R>(&self, f: F) -> R
350 where
351 F: FnOnce(&mut T) -> R,
352 {
353 let mut data = self.data.write();
354 f(&mut data)
355 }
356
357 /// Sets new data and notifies waiting threads
358 ///
359 /// This method replaces the current data and notifies all threads
360 /// waiting for changes.
361 ///
362 /// ## Arguments
363 ///
364 /// * `new_data` - The new data to set
365 ///
366 /// ## Example
367 ///
368 /// ```rust
369 /// use thread_share::ThreadShare;
370 /// use std::thread;
371 ///
372 /// let data = ThreadShare::new(0);
373 /// let clone = data.clone();
374 ///
375 /// thread::spawn(move || {
376 /// clone.set(100);
377 /// });
378 ///
379 /// data.wait_for_change_forever();
380 /// assert_eq!(data.get(), 100);
381 /// ```
382 pub fn set(&self, new_data: T) {
383 let mut data = self.data.write();
384 *data = new_data;
385 self.condvar.notify_all();
386 }
387
388 /// Updates data using a function and notifies waiting threads
389 ///
390 /// This method allows you to modify the data through a closure and
391 /// automatically notifies waiting threads of the change.
392 ///
393 /// ## Arguments
394 ///
395 /// * `f` - Closure that receives a mutable reference to the data
396 ///
397 /// ## Example
398 ///
399 /// ```rust
400 /// use thread_share::ThreadShare;
401 ///
402 /// let counter = ThreadShare::new(0);
403 ///
404 /// counter.update(|x| *x += 1);
405 /// assert_eq!(counter.get(), 1);
406 ///
407 /// counter.update(|x| *x *= 2);
408 /// assert_eq!(counter.get(), 2);
409 /// ```
410 pub fn update<F>(&self, f: F)
411 where
412 F: FnOnce(&mut T),
413 {
414 let mut data = self.data.write();
415 f(&mut data);
416 self.condvar.notify_all();
417 }
418
419 /// Waits for data changes with timeout
420 ///
421 /// This method waits for a change notification with a specified timeout.
422 ///
423 /// ## Arguments
424 ///
425 /// * `timeout` - Maximum time to wait for changes
426 ///
427 /// ## Returns
428 ///
429 /// `true` if the timeout was reached, `false` if a change occurred.
430 ///
431 /// ## Example
432 ///
433 /// ```rust
434 /// use thread_share::ThreadShare;
435 /// use std::time::Duration;
436 ///
437 /// let data = ThreadShare::new(0);
438 /// let clone = data.clone();
439 ///
440 /// // Spawn thread that will change data after 200ms
441 /// std::thread::spawn(move || {
442 /// std::thread::sleep(Duration::from_millis(200));
443 /// clone.set(100);
444 /// });
445 ///
446 /// // Wait for change with 100ms timeout
447 /// let timed_out = data.wait_for_change(Duration::from_millis(100));
448 /// assert!(timed_out); // Should timeout
449 ///
450 /// // Wait for change with 300ms timeout
451 /// let timed_out = data.wait_for_change(Duration::from_millis(300));
452 /// assert!(!timed_out); // Should not timeout
453 /// ```
454 pub fn wait_for_change(&self, timeout: Duration) -> bool {
455 let guard = self.receiver.lock().unwrap();
456 let result = self.condvar.wait_timeout(guard, timeout).unwrap();
457 result.1.timed_out()
458 }
459
460 /// Waits for data changes infinitely
461 ///
462 /// This method waits indefinitely for a change notification.
463 ///
464 /// ## Example
465 ///
466 /// ```rust
467 /// use thread_share::ThreadShare;
468 /// use std::thread;
469 /// use std::time::Duration;
470 ///
471 /// let data = ThreadShare::new(0);
472 /// let clone = data.clone();
473 ///
474 /// thread::spawn(move || {
475 /// thread::sleep(Duration::from_millis(100));
476 /// clone.set(100);
477 /// });
478 ///
479 /// // Wait indefinitely for change
480 /// data.wait_for_change_forever();
481 /// assert_eq!(data.get(), 100);
482 /// ```
483 pub fn wait_for_change_forever(&self) {
484 let guard = self.receiver.lock().unwrap();
485 let _unused = self.condvar.wait(guard).unwrap();
486 }
487
488 /// Creates a clone for use in another thread
489 ///
490 /// This method creates a new `ThreadShare<T>` instance that shares
491 /// the same underlying data. Each clone can be safely moved to
492 /// different threads.
493 ///
494 /// ## Returns
495 ///
496 /// A new `ThreadShare<T>` instance sharing the same data.
497 ///
498 /// ## Example
499 ///
500 /// ```rust
501 /// use thread_share::ThreadShare;
502 /// use std::thread;
503 /// use std::time::Duration;
504 ///
505 /// let data = ThreadShare::new(0);
506 /// let clone1 = data.clone();
507 /// let clone2 = data.clone();
508 ///
509 /// // Each clone can be used in different threads
510 /// thread::spawn(move || {
511 /// clone1.set(100);
512 /// });
513 ///
514 /// thread::spawn(move || {
515 /// clone2.set(200);
516 /// });
517 ///
518 /// // Main thread waits for changes
519 /// data.wait_for_change_forever();
520 /// ```
521 pub fn clone(&self) -> Self {
522 Self {
523 data: Arc::clone(&self.data),
524 sender: Arc::clone(&self.sender),
525 receiver: Arc::clone(&self.receiver),
526 condvar: Arc::clone(&self.condvar),
527 }
528 }
529
530 /// Gets Arc on data for transfer to thread without cloning
531 ///
532 /// This method converts the `ThreadShare<T>` into an `Arc<RwLock<T>>`,
533 /// which can be moved into threads without cloning the `ThreadShare` itself.
534 ///
535 /// ## Returns
536 ///
537 /// An `Arc<RwLock<T>>` containing the shared data.
538 ///
539 /// ## Example
540 ///
541 /// ```rust
542 /// use thread_share::ThreadShare;
543 /// use std::thread;
544 ///
545 /// let data = ThreadShare::new(0);
546 /// let arc_data = data.into_arc();
547 ///
548 /// thread::spawn(move || {
549 /// let mut guard = arc_data.write();
550 /// *guard += 100;
551 /// });
552 /// ```
553 pub fn into_arc(self) -> Arc<RwLock<T>> {
554 self.data
555 }
556
557 /// Gets Arc<RwLock<T>> for version with locks
558 ///
559 /// This method returns an `Arc<RwLock<T>>` that shares the same data
560 /// as this `ThreadShare<T>`. This is useful when you need to work
561 /// directly with the underlying `Arc<RwLock<T>>` structure.
562 ///
563 /// ## Returns
564 ///
565 /// An `Arc<RwLock<T>>` sharing the same data.
566 ///
567 /// ## Example
568 ///
569 /// ```rust
570 /// use thread_share::ThreadShare;
571 ///
572 /// let data = ThreadShare::new(vec![1, 2, 3]);
573 /// let arc_data = data.as_arc_locked();
574 ///
575 /// // Use the Arc<RwLock<T>> directly
576 /// let mut guard = arc_data.write();
577 /// guard.push(4);
578 /// drop(guard);
579 ///
580 /// // Changes are visible in the original ThreadShare
581 /// assert_eq!(data.get(), vec![1, 2, 3, 4]);
582 /// ```
583 pub fn as_arc_locked(&self) -> Arc<RwLock<T>> {
584 Arc::clone(&self.data)
585 }
586
587 /// Gets Arc on data for transfer to thread without cloning (reference)
588 ///
589 /// This method creates an `Arc<AtomicPtr<T>>` from the current data.
590 /// **Warning**: This creates an independent copy of the data, not a shared reference.
591 /// Changes to the returned `Arc<AtomicPtr<T>>` will not be visible in the original `ThreadShare<T>`.
592 ///
593 /// ## Requirements
594 ///
595 /// The type `T` must implement `Clone` trait.
596 ///
597 /// ## Returns
598 ///
599 /// An `Arc<AtomicPtr<T>>` containing a copy of the current data.
600 ///
601 /// ## Warning
602 ///
603 /// This method creates an **independent copy** of the data. Use `as_arc_locked()` if you
604 /// need a shared reference to the same data.
605 ///
606 /// ## Example
607 ///
608 /// ```rust
609 /// use thread_share::ThreadShare;
610 ///
611 /// let data = ThreadShare::new(vec![1, 2, 3]);
612 /// let arc_data = data.as_arc();
613 ///
614 /// // This modifies the copy, not the original
615 /// // Use ArcThreadShare::from_arc(arc_data) to work with it
616 /// ```
617 pub fn as_arc(&self) -> Arc<std::sync::atomic::AtomicPtr<T>>
618 where
619 T: Clone,
620 {
621 // Create AtomicPtr from current data
622 let current_data = self.data.read();
623 let cloned_data = (*current_data).clone();
624 let boxed = Box::new(cloned_data);
625 let ptr = Box::into_raw(boxed);
626 Arc::new(std::sync::atomic::AtomicPtr::new(ptr))
627 }
628}
629
630impl<T> Clone for ThreadShare<T> {
631 fn clone(&self) -> Self {
632 self.clone()
633 }
634}
635
636/// Simplified version for simple types
637pub struct SimpleShare<T> {
638 data: Arc<Mutex<T>>,
639}
640
641// Automatically implement Send and Sync for SimpleShare
642unsafe impl<T> Send for SimpleShare<T> {}
643unsafe impl<T> Sync for SimpleShare<T> {}
644
645impl<T> SimpleShare<T> {
646 /// Creates a new SimpleShare
647 ///
648 /// This method creates a new `SimpleShare<T>` instance with the provided data.
649 /// SimpleShare is a simplified version of ThreadShare without change detection.
650 ///
651 /// ## Arguments
652 ///
653 /// * `data` - The initial data to share between threads
654 ///
655 /// ## Returns
656 ///
657 /// A new `SimpleShare<T>` instance containing the data.
658 ///
659 /// ## Example
660 ///
661 /// ```rust
662 /// use thread_share::SimpleShare;
663 ///
664 /// let counter = SimpleShare::new(0);
665 /// let message = SimpleShare::new(String::from("Hello"));
666 /// let data = SimpleShare::new(vec![1, 2, 3]);
667 /// ```
668 pub fn new(data: T) -> Self {
669 Self {
670 data: Arc::new(Mutex::new(data)),
671 }
672 }
673
674 /// Gets data
675 ///
676 /// This method retrieves a copy of the current data. The operation is safe
677 /// but involves cloning the data.
678 ///
679 /// ## Requirements
680 ///
681 /// The type `T` must implement `Clone` trait.
682 ///
683 /// ## Returns
684 ///
685 /// A copy of the current data.
686 ///
687 /// ## Example
688 ///
689 /// ```rust
690 /// use thread_share::SimpleShare;
691 ///
692 /// let counter = SimpleShare::new(42);
693 /// let value = counter.get();
694 /// assert_eq!(value, 42);
695 /// ```
696 pub fn get(&self) -> T
697 where
698 T: Clone,
699 {
700 self.data.lock().unwrap().clone()
701 }
702
703 /// Sets data
704 ///
705 /// This method replaces the current data with new data.
706 ///
707 /// ## Arguments
708 ///
709 /// * `new_data` - The new data to set
710 ///
711 /// ## Example
712 ///
713 /// ```rust
714 /// use thread_share::SimpleShare;
715 ///
716 /// let counter = SimpleShare::new(0);
717 /// counter.set(100);
718 /// assert_eq!(counter.get(), 100);
719 /// ```
720 pub fn set(&self, new_data: T) {
721 let mut data = self.data.lock().unwrap();
722 *data = new_data;
723 }
724
725 /// Updates data
726 ///
727 /// This method allows you to modify the data through a closure.
728 ///
729 /// ## Arguments
730 ///
731 /// * `f` - Closure that receives a mutable reference to the data
732 ///
733 /// ## Example
734 ///
735 /// ```rust
736 /// use thread_share::SimpleShare;
737 ///
738 /// let counter = SimpleShare::new(0);
739 ///
740 /// counter.update(|x| *x += 1);
741 /// assert_eq!(counter.get(), 1);
742 ///
743 /// counter.update(|x| *x *= 2);
744 /// assert_eq!(counter.get(), 2);
745 /// ```
746 pub fn update<F>(&self, f: F)
747 where
748 F: FnOnce(&mut T),
749 {
750 let mut data = self.data.lock().unwrap();
751 f(&mut data);
752 }
753
754 /// Clones for use in another thread
755 ///
756 /// This method creates a new `SimpleShare<T>` instance that shares
757 /// the same underlying data. Each clone can be safely moved to
758 /// different threads.
759 ///
760 /// ## Returns
761 ///
762 /// A new `SimpleShare<T>` instance sharing the same data.
763 ///
764 /// ## Example
765 ///
766 /// ```rust
767 /// use thread_share::SimpleShare;
768 /// use std::thread;
769 ///
770 /// let data = SimpleShare::new(0);
771 /// let clone1 = data.clone();
772 /// let clone2 = data.clone();
773 ///
774 /// // Each clone can be used in different threads
775 /// thread::spawn(move || {
776 /// clone1.set(100);
777 /// });
778 ///
779 /// thread::spawn(move || {
780 /// clone2.set(200);
781 /// });
782 /// ```
783 pub fn clone(&self) -> Self {
784 Self {
785 data: Arc::clone(&self.data),
786 }
787 }
788
789 /// Gets Arc on data for transfer to thread without cloning
790 ///
791 /// This method consumes the `SimpleShare<T>` and returns the underlying
792 /// `Arc<Mutex<T>>`. This is useful when you need to work directly
793 /// with the `Arc<Mutex<T>>` structure.
794 ///
795 /// ## Returns
796 ///
797 /// The underlying `Arc<Mutex<T>>` containing the shared data.
798 ///
799 /// ## Example
800 ///
801 /// ```rust
802 /// use thread_share::SimpleShare;
803 ///
804 /// let data = SimpleShare::new(vec![1, 2, 3]);
805 /// let arc_data = data.into_arc();
806 ///
807 /// // Use the Arc<Mutex<T>> directly
808 /// let mut guard = arc_data.lock().unwrap();
809 /// guard.push(4);
810 /// drop(guard);
811 /// ```
812 pub fn into_arc(self) -> Arc<Mutex<T>> {
813 self.data
814 }
815
816 /// Gets Arc on data for transfer to thread without cloning (reference)
817 ///
818 /// This method returns an `Arc<Mutex<T>>` that shares the same data
819 /// as this `SimpleShare<T>`. This is useful when you need to work
820 /// directly with the underlying `Arc<Mutex<T>>` structure.
821 ///
822 /// ## Returns
823 ///
824 /// An `Arc<Mutex<T>>` sharing the same data.
825 ///
826 /// ## Example
827 ///
828 /// ```rust
829 /// use thread_share::SimpleShare;
830 ///
831 /// let data = SimpleShare::new(vec![1, 2, 3]);
832 /// let arc_data = data.as_arc();
833 ///
834 /// // Use the Arc<Mutex<T>> directly
835 /// let mut guard = arc_data.lock().unwrap();
836 /// guard.push(4);
837 /// drop(guard);
838 ///
839 /// // Changes are visible in the original SimpleShare
840 /// assert_eq!(data.get(), vec![1, 2, 3, 4]);
841 /// ```
842 pub fn as_arc(&self) -> Arc<Mutex<T>> {
843 Arc::clone(&self.data)
844 }
845}
846
847impl<T> Clone for SimpleShare<T> {
848 fn clone(&self) -> Self {
849 self.clone()
850 }
851}