1 // Copyright (c) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 //! This example simulates the situation of task starvation by spawning long 15 //! tasks that have no await point 16 17 use std::thread; 18 use std::time::Duration; 19 20 use tokio::time::Instant; 21 main()22fn main() { 23 // initialize the runtime with only 1 worker thread 24 ylong_runtime::builder::RuntimeBuilder::new_multi_thread() 25 .worker_num(1) 26 .build_global() 27 .unwrap(); 28 29 let instant = Instant::now(); 30 let _long_hold = ylong_runtime::spawn(async move { 31 thread::sleep(Duration::from_secs(5)); 32 }); 33 let handle = ylong_runtime::spawn(async move { 34 let a = 0; 35 assert_eq!(a, 0); 36 }); 37 ylong_runtime::block_on(handle).unwrap(); 38 let time_cost = instant.elapsed().as_secs(); 39 println!("time cost: {}", time_cost); 40 assert!(time_cost >= 5); 41 } 42