Technology Sharing

rust way step 7

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

  1. use std::{sync::mpsc, thread, time::Duration};
  2. fn spawn_function() {
  3. for i in 0..5 {
  4. println!("spawned thread print {}", i);
  5. thread::sleep(Duration::from_millis(1));
  6. }
  7. }
  8. #[tokio::main]
  9. async fn main() {
  10. thread::spawn(spawn_function);
  11. thread::spawn(|| {
  12. for i in 0..5 {
  13. println!("spawned thread printa {}", i);
  14. thread::sleep(Duration::from_millis(1));
  15. }
  16. });
  17. let (tx, rx) = mpsc::channel();
  18. thread::spawn(move || {
  19. let val = String::from("hi............");
  20. tx.send(val).unwrap();
  21. });
  22. let received = rx.recv().unwrap();
  23. println!("Got: {}", received);
  24. let s = "hello";
  25. let handle = thread::spawn(move || {
  26. println!("{}", s);
  27. });
  28. handle.join().unwrap();
  29. thread::sleep(Duration::from_secs(1));
  30. /*************************************************************************/
  31. async fn async_task() -> u32 {
  32. tokio::time::sleep(std::time::Duration::from_secs(1)).await;
  33. return 999;
  34. }
  35. // 异步任务执行函数
  36. async fn execute_async_task() {
  37. // 调用异步任务,并等待其完成
  38. let result = async_task().await;
  39. // 输出结果
  40. println!("Async task result: {}", result);
  41. }
  42. execute_async_task().await;
  43. println!("Async task completed!");
  44. async fn hello() -> String {
  45. "Hello, world!".to_string()
  46. }
  47. async fn print_hello() {
  48. let result = hello().await;
  49. println!("{}", result);
  50. }
  51. print_hello().await;
  52. thread::sleep(Duration::from_secs(2));
  53. }

tokio = { version = "1.0.0", features = ["full"] }