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 //! Now `sdv_mutex` only has one test. In this test, `sleep` is called,
15 //! requiring to initialize time driver by `driver::Driver::get_mut_driver()`.
16 //! This initialization will only be called in `RuntimeBuilder::build()` when
17 //! `net` feature is open. Therefore, temporarily mark the whole test file so
18 //! that it will only run when these features are open. If more tests are added
19 //! in the future, this conditionally compiling macro should be moved to
20 //! mark the test `sdv_mutex_lock_hold_longtime`.
21
22 #![cfg(all(feature = "sync", feature = "time"))]
23
24 use std::sync::Arc;
25 use std::thread;
26 use std::time::Duration;
27
28 use ylong_runtime::sync::Mutex;
29 use ylong_runtime::time;
30
31 /// SDV test cases for Mutex::lock() interface
32 ///
33 /// # Brief
34 /// 1. Create a Concurrent Mutual Exclusion Lock.
35 /// 2. Make a concurrent process obtain a concurrent mutex lock and sleep after
36 /// obtaining it to hold the lock for a long time.
37 /// 3. The main thread creates a new concurrent thread to perform the locking
38 /// operation, and then modifies the value in the lock after obtaining the
39 /// lock.
40 /// 4. Check the value in the lock.
41 #[test]
sdv_mutex_lock_hold_longtime()42 fn sdv_mutex_lock_hold_longtime() {
43 let mutex = Arc::new(Mutex::new(10));
44 let mutex1 = mutex.clone();
45 let handle = ylong_runtime::spawn(async move {
46 let mut lock = mutex1.lock().await;
47 *lock += 1;
48 time::sleep(Duration::new(1, 5000)).await;
49 });
50 thread::sleep(Duration::new(1, 00));
51 ylong_runtime::block_on(async {
52 let mut lock2 = mutex.lock().await;
53 *lock2 += 1;
54 assert_eq!(*lock2, 12);
55 });
56 let _ = ylong_runtime::block_on(handle);
57 }
58