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 use std::cell::RefCell; 15 use std::sync::Arc; 16 use std::thread; 17 18 #[cfg(feature = "time")] 19 use crate::time::TimeDriver; 20 21 #[cfg(any(not(feature = "ffrt"), all(feature = "net", feature = "ffrt")))] 22 const NET_POLL_INTERVAL_TIME: std::time::Duration = std::time::Duration::from_millis(10); 23 24 /// Net poller thread creation and management 25 #[derive(Clone)] 26 pub(crate) struct NetLooper { 27 inner: Arc<Inner>, 28 } 29 30 unsafe impl Send for NetLooper {} 31 unsafe impl Sync for NetLooper {} 32 33 struct Inner { 34 join_handle: RefCell<Option<thread::JoinHandle<()>>>, 35 } 36 37 impl NetLooper { new() -> Self38 pub(crate) fn new() -> Self { 39 NetLooper { 40 inner: Arc::new(Inner { 41 join_handle: RefCell::new(None), 42 }), 43 } 44 } 45 create_net_poller_thread(&self)46 pub(crate) fn create_net_poller_thread(&self) { 47 // todo: now we use the default thread stack size, could be smaller 48 let builder = thread::Builder::new().name("yl_net_poller".to_string()); 49 let netpoller_handle = self.clone(); 50 51 let result = builder.spawn(move || netpoller_handle.run()); 52 match result { 53 Ok(join_handle) => { 54 *self.inner.join_handle.borrow_mut() = Some(join_handle); 55 } 56 Err(e) => panic!("os cannot spawn the monitor thread: {}", e), 57 } 58 } 59 run(&self)60 fn run(&self) { 61 loop { 62 // run time driver 63 #[cfg(feature = "time")] 64 TimeDriver::get_ref().run(); 65 66 thread::sleep(NET_POLL_INTERVAL_TIME); 67 } 68 } 69 } 70