pub struct ThreadShare<T> { /* private fields */ }Expand description
Main structure for data exchange between threads
ThreadShare<T> provides comprehensive thread synchronization with automatic
change detection and efficient locking mechanisms.
§Features
- Automatic Cloning: Each thread gets its own clone for safe access
- Change Detection: Built-in waiting mechanisms for data changes
- Flexible Access: Read, write, and update operations with proper locking
- Condition Variables: Efficient waiting for data modifications
- Thread Safety: Implements
SendandSyncautomatically
§Example
use thread_share::ThreadShare;
use std::thread;
let data = ThreadShare::new(vec![1, 2, 3]);
let clone = data.clone();
thread::spawn(move || {
clone.update(|v| v.push(4));
});
data.wait_for_change_forever();
assert_eq!(data.get(), vec![1, 2, 3, 4]);§Performance
- Read Operations: Multiple threads can read simultaneously
- Write Operations: Exclusive access during writes
- Change Detection: Efficient condition variable notifications
- Memory Overhead: Minimal overhead from Arc and RwLock structures
Implementations§
Sourcepub fn to_json(&self) -> Result<String, String>
pub fn to_json(&self) -> Result<String, String>
Serializes the current data to JSON string
This method requires the serialize feature to be enabled.
§Returns
JSON string representation of the data, or error string if serialization fails.
§Example
use thread_share::ThreadShare;
#[cfg(feature = "serialize")]
{
let data = ThreadShare::new(vec![1, 2, 3]);
let json = data.to_json().expect("Failed to serialize");
assert_eq!(json, "[1,2,3]");
}Sourcepub fn from_json(&self, json: &str) -> Result<(), String>
pub fn from_json(&self, json: &str) -> Result<(), String>
Deserializes data from JSON string
This method requires the serialize feature to be enabled.
§Arguments
json- JSON string to deserialize
§Returns
Ok(()) on success, Err(String) if deserialization fails.
§Example
use thread_share::ThreadShare;
#[cfg(feature = "serialize")]
{
let data = ThreadShare::new(vec![0; 0]);
data.from_json("[1,2,3]").expect("Failed to deserialize");
assert_eq!(data.get(), vec![1, 2, 3]);
}Sourcepub fn read<F, R>(&self, f: F) -> R
pub fn read<F, R>(&self, f: F) -> R
Gets a reference to data for reading
This method provides read-only access to the data through a closure. Multiple threads can read simultaneously.
§Arguments
f- Closure that receives a reference to the data
§Returns
The result of the closure execution.
§Example
use thread_share::ThreadShare;
let data = ThreadShare::new(vec![1, 2, 3]);
let length = data.read(|v| v.len());
assert_eq!(length, 3);
let sum: i32 = data.read(|v| v.iter().sum());
assert_eq!(sum, 6);Sourcepub fn write<F, R>(&self, f: F) -> R
pub fn write<F, R>(&self, f: F) -> R
Gets a mutable reference to data
This method provides mutable access to the data through a closure. Only one thread can write at a time.
§Arguments
f- Closure that receives a mutable reference to the data
§Returns
The result of the closure execution.
§Example
use thread_share::ThreadShare;
let data = ThreadShare::new(vec![1, 2, 3]);
let length = data.write(|v| {
v.push(4);
v.len()
});
assert_eq!(length, 4);
assert_eq!(data.get(), vec![1, 2, 3, 4]);Sourcepub fn set(&self, new_data: T)
pub fn set(&self, new_data: T)
Sets new data and notifies waiting threads
This method replaces the current data and notifies all threads waiting for changes.
§Arguments
new_data- The new data to set
§Example
use thread_share::ThreadShare;
use std::thread;
let data = ThreadShare::new(0);
let clone = data.clone();
thread::spawn(move || {
clone.set(100);
});
data.wait_for_change_forever();
assert_eq!(data.get(), 100);Sourcepub fn update<F>(&self, f: F)
pub fn update<F>(&self, f: F)
Updates data using a function and notifies waiting threads
This method allows you to modify the data through a closure and automatically notifies waiting threads of the change.
§Arguments
f- Closure that receives a mutable reference to the data
§Example
use thread_share::ThreadShare;
let counter = ThreadShare::new(0);
counter.update(|x| *x += 1);
assert_eq!(counter.get(), 1);
counter.update(|x| *x *= 2);
assert_eq!(counter.get(), 2);Sourcepub fn wait_for_change(&self, timeout: Duration) -> bool
pub fn wait_for_change(&self, timeout: Duration) -> bool
Waits for data changes with timeout
This method waits for a change notification with a specified timeout.
§Arguments
timeout- Maximum time to wait for changes
§Returns
true if the timeout was reached, false if a change occurred.
§Example
use thread_share::ThreadShare;
use std::time::Duration;
let data = ThreadShare::new(0);
let clone = data.clone();
// Spawn thread that will change data after 200ms
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
clone.set(100);
});
// Wait for change with 100ms timeout
let timed_out = data.wait_for_change(Duration::from_millis(100));
assert!(timed_out); // Should timeout
// Wait for change with 300ms timeout
let timed_out = data.wait_for_change(Duration::from_millis(300));
assert!(!timed_out); // Should not timeoutSourcepub fn wait_for_change_forever(&self)
pub fn wait_for_change_forever(&self)
Waits for data changes infinitely
This method waits indefinitely for a change notification.
§Example
use thread_share::ThreadShare;
use std::thread;
use std::time::Duration;
let data = ThreadShare::new(0);
let clone = data.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(100));
clone.set(100);
});
// Wait indefinitely for change
data.wait_for_change_forever();
assert_eq!(data.get(), 100);Sourcepub fn clone(&self) -> Self
pub fn clone(&self) -> Self
Creates a clone for use in another thread
This method creates a new ThreadShare<T> instance that shares
the same underlying data. Each clone can be safely moved to
different threads.
§Returns
A new ThreadShare<T> instance sharing the same data.
§Example
use thread_share::ThreadShare;
use std::thread;
use std::time::Duration;
let data = ThreadShare::new(0);
let clone1 = data.clone();
let clone2 = data.clone();
// Each clone can be used in different threads
thread::spawn(move || {
clone1.set(100);
});
thread::spawn(move || {
clone2.set(200);
});
// Main thread waits for changes
data.wait_for_change_forever();Sourcepub fn into_arc(self) -> Arc<RwLock<T>>
pub fn into_arc(self) -> Arc<RwLock<T>>
Gets Arc on data for transfer to thread without cloning
This method converts the ThreadShare<T> into an Arc<RwLock<T>>,
which can be moved into threads without cloning the ThreadShare itself.
§Returns
An Arc<RwLock<T>> containing the shared data.
§Example
use thread_share::ThreadShare;
use std::thread;
let data = ThreadShare::new(0);
let arc_data = data.into_arc();
thread::spawn(move || {
let mut guard = arc_data.write();
*guard += 100;
});Sourcepub fn as_arc_locked(&self) -> Arc<RwLock<T>>
pub fn as_arc_locked(&self) -> Arc<RwLock<T>>
Gets Arc<RwLock
This method returns an Arc<RwLock<T>> that shares the same data
as this ThreadShare<T>. This is useful when you need to work
directly with the underlying Arc<RwLock<T>> structure.
§Returns
An Arc<RwLock<T>> sharing the same data.
§Example
use thread_share::ThreadShare;
let data = ThreadShare::new(vec![1, 2, 3]);
let arc_data = data.as_arc_locked();
// Use the Arc<RwLock<T>> directly
let mut guard = arc_data.write();
guard.push(4);
drop(guard);
// Changes are visible in the original ThreadShare
assert_eq!(data.get(), vec![1, 2, 3, 4]);Sourcepub fn as_arc(&self) -> Arc<AtomicPtr<T>>where
T: Clone,
pub fn as_arc(&self) -> Arc<AtomicPtr<T>>where
T: Clone,
Gets Arc on data for transfer to thread without cloning (reference)
This method creates an Arc<AtomicPtr<T>> from the current data.
Warning: This creates an independent copy of the data, not a shared reference.
Changes to the returned Arc<AtomicPtr<T>> will not be visible in the original ThreadShare<T>.
§Requirements
The type T must implement Clone trait.
§Returns
An Arc<AtomicPtr<T>> containing a copy of the current data.
§Warning
This method creates an independent copy of the data. Use as_arc_locked() if you
need a shared reference to the same data.
§Example
use thread_share::ThreadShare;
let data = ThreadShare::new(vec![1, 2, 3]);
let arc_data = data.as_arc();
// This modifies the copy, not the original
// Use ArcThreadShare::from_arc(arc_data) to work with it