#clucompany #no-std #easy-sync-code

no-std synchronized

多线程代码同步的便捷简单宏

5 个稳定版本

1.0.4 2022年12月25日
1.0.3 2022年9月4日
1.0.2 2022年8月31日
1.0.1 2022年8月18日
1.0.0 2022年8月17日

#286并发

Apache-2.0

49KB
683

synchronized

CI Apache licensed crates.io Documentation

多线程代码同步的便捷简单宏。

使用

1. easy/sync

use synchronized::synchronized;

/*
	Quick implementation examples of blocking anonymous code.
*/

fn main() {
	// #1 Anonymous inter-threaded synchronized code, 
	// in the case of multi-threading, one thread will wait for the completion of another.
	synchronized! {
		println!("1");
	}
	
	// #2 Anonymous inter-threaded synchronized code, 
	// in the case of multi-threading, one thread will wait for the completion of another.
	synchronized!( println!("1"); );
}

2. sync_static

use std::thread::spawn;
use synchronized::synchronized;

/*
	A more illustrative example of code blocking implementation 
	for SAFE mutability of two or more static variables.
	
	The code creates 5 threads that try to change static variables at the same 
	time without synchronization, but the code synchronization block 
	does not allow this code to execute at the same time, which makes 
	the implementation of changing static variables SAFE and even somewhat 
	easier and more beneficial in terms of use and performance.
*/

fn main() {
	// An array of handles to wait for all threads to complete.
	let mut join_all = Vec::new();
	
	// Creation of 5 threads to implement a multi-threaded environment.
	for thread_id in 0..5 {
		let join = spawn(move || {
			// Print the thread number and print the 
			// result of the sync_fn function.
			println!("#[id: {}] {}", thread_id, sync_fn());
		});
		
		join_all.push(join);
	}
	
	// We just wait for all threads to finish and look at stdout.
	for tjoin in join_all {
		let _e = tjoin.join();
	}
}

fn sync_fn() -> usize {
	// Create anonymous synchronized code.
	//
	// The code will never run at the same time. If one thread is executing 
	// this code, the second thread will wait for this code to finish executing.
	let result = synchronized! {
		static mut POINT0: usize = 0;
		static mut POINT1: usize = 0;
		
		unsafe {
			POINT1 = POINT0;
			POINT0 += 1;
			
			POINT1
		}
	};
	
	result
}

3. sync_let

use std::thread::spawn;
use synchronized::synchronized;

/*
	An example that describes how to quickly create an anonymous 
	sync with a mutable variable.
	
	This code creates 5 threads, each of which tries to update 
	the `sync_let` variable with data while executing the synchronized anonymous code.
*/

fn main() {
	// An array of handles to wait for all threads to complete.
	let mut join_all = Vec::new();
	
	// Creation of 5 threads to implement a multi-threaded environment.
	for thread_id in 0..5 {
		let join = spawn(move || {
			// Create anonymous synchronized code with one mutable variable `sync_let` and `count`.
			let result = synchronized!(
				(sync_let: String = String::new(), count: usize = 0) {
					// If it's the first thread, 
					// then theoretically `sync_let` is String::new().
					if thread_id == 0 {
						assert_eq!(sync_let.is_empty(), true);
						assert_eq!(count, &0);
					}
					
					// We fill the variable `sync_let` and `count` with data.
					sync_let.push_str(&thread_id.to_string());
					sync_let.push_str(" ");
					
					*count += 1;
					
					sync_let.clone()
				}
			);
			
			// Outputting debug information.
			println!("#[id: {}] {}", thread_id, result);
		});
		
		// In order for our `assert_eq!(sync_let.is_empty());` code to 
		// always run correctly, the first thread should always run first 
		// (this is just for the stability of this example).
		if thread_id == 0 {
			let _e = join.join();
			continue;
		}
		
		join_all.push(join);
	}
	
	// We just wait for all threads to finish and look at stdout.
	for tjoin in join_all {
		let _e = tjoin.join();
	}
}

4. point

/*
	An example implementation of synchronized code with 
	one non-anonymous synchronization point.
	
	This example creates a set of anonymous sync codes associated with a 
	single named sync point. Each synchronization code executes in the same 
	way as ordinary anonymous code, but execution occurs simultaneously in a 
	multi-threaded environment in only one of them.
	
	!!! In this example, the assembly requires the `point` feature to be active.
*/

#[cfg( feature = "point" )]
use synchronized::synchronized_point;
#[cfg( feature = "point" )]
use synchronized::synchronized;

#[cfg( not(feature = "point") )]
macro_rules! synchronized_point {
	[ $($unk:tt)* ] => {
		println!("!!! This example requires support for the `point` feature. Run the example with `cargo run --example point --all-features`.");
	};
}

fn main() {
	// A sync point named `COMB_SYNC` to group anonymous code syncs by name.
	synchronized_point! {(COMB_SYNC) {
		static mut POINT: usize = 0;
		println!("GeneralSyncPoint, name_point: {}", COMB_SYNC.get_sync_point_name());
		
		// #1 Anonymous synchronized code that operates on a 
		// single named synchronization point.
		//
		// This code is not executed concurrently in a multi-threaded environment, 
		// one thread is waiting for someone else's code to execute in this part of the code.
		let result0 = synchronized! ((->COMB_SYNC) {
			println!("SyncCode, name_point: {}", COMB_SYNC.get_sync_point_name());
			unsafe {
				POINT += 1;
				
				POINT
			}
		});
		
		// This line of code is not synchronized and can run concurrently on all threads.
		println!("Unsynchronized code");
		
		// #2 Anonymous synchronized code that operates on a 
		// single named synchronization point.
		//
		// Note that `result0` and `result1` cannot be calculated at the same time, 
		// this does not happen because `result0` or `result1` are calculated in 
		// synchronized code with a single sync point of the same name.
		let result1 = synchronized! ((->COMB_SYNC) {
			println!("SyncCode, name_point: {}", COMB_SYNC.get_sync_point_name());
			unsafe {
				POINT += 1;
				
				POINT
			}
		});
		
		// Display debug information.
		println!("result, res0: {:?}, res1: {:?}", result0, result1);
	}}
}

连接

本节仅描述如何为 synchronized 宏选择默认的同步方法。

1. 即插即用(最小化,sync,std)

对于 synchronized 宏,使用默认 std 库实现的原语。

[dependencies.synchronized]
version = "1.0.4"
default-features = false
features = [
	"std",
	#"point",
	#"get_point_name"
]

2. 即插即用(最小化,sync,parking_lot)

对于 synchronized 宏,使用默认 parking_lot 库实现的原语。

[dependencies.synchronized]
version = "1.0.4"
default-features = false
features = [
	"parking_lot",
	#"point",
	#"get_point_name"
]

3. 即插即用(最小化,异步,tokio+parking_lot+async_trait)

对于 synchronized 宏,使用默认 tokio 库实现的原语。

[dependencies.synchronized]
version = "1.0.4"
default-features = false
features = [
	"async",
	#"point",
	#"get_point_name"
]

此外...

  1. 该宏是 Rust 编程语言中针对 Java 编程语言的各种扩展的 synchronized 关键字的替代品。

  2. 此宏由一位很长时间没有写 Java 的作者创建,受 Java 编程语言(版本 1.5-1.6)的启发。

许可证

版权所有 2022 #UlinProject Denis Kotlyarov (Денис Котляров)

根据 Apache License,版本 2.0 许可

依赖关系

~0–6.5MB
~24K SLoC