@@ -777,26 +777,26 @@ public:
777
777
778
778
std::recursive_mutex mtx;
779
779
780
- void recursiveFunction (int count) {
780
+ void recursive_function (int count) {
781
781
// 递归函数,每次递归都会锁定互斥量
782
782
mtx.lock();
783
783
std::cout << "Locked by thread: " << std::this_thread::get_id() << ", count: " << count << std::endl;
784
784
if (count > 0) {
785
- recursiveFunction (count - 1); // 递归调用
785
+ recursive_function (count - 1); // 递归调用
786
786
}
787
787
mtx.unlock(); // 解锁互斥量
788
788
}
789
789
790
790
int main() {
791
- std::thread t1(recursiveFunction , 3);
792
- std::thread t2(recursiveFunction , 2);
791
+ std::thread t1(recursive_function , 3);
792
+ std::thread t2(recursive_function , 2);
793
793
794
794
t1.join();
795
795
t2.join();
796
796
}
797
797
```
798
798
799
- > [运行](https://godbolt.org/z/58z41MrxP )测试。
799
+ > [运行](https://godbolt.org/z/aefrYbGd7 )测试。
800
800
801
801
- [**`lock`**](https://zh.cppreference.com/w/cpp/thread/recursive_mutex/lock):线程可以在递归互斥体上重复调用 `lock`。在线程调用 `unlock` 匹配次数后,所有权才会得到**释放**。
802
802
@@ -807,16 +807,16 @@ int main() {
807
807
同样的,我们也可以使用 `std::lock_guard`、`std::unique_lock` 帮我们管理 `std::recursive_mutex`,而非显式调用 `lock` 与 `unlock`:
808
808
809
809
```cpp
810
- void recursiveFunction (int count) {
810
+ void recursive_function (int count) {
811
811
std::lock_guard<std::recursive_mutex>lc{ mtx };
812
812
std::cout << "Locked by thread: " << std::this_thread::get_id() << ", count: " << count << std::endl;
813
813
if (count > 0) {
814
- recursiveFunction (count - 1);
814
+ recursive_function (count - 1);
815
815
}
816
816
}
817
817
```
818
818
819
- > [ 运行] ( https://godbolt.org/z/6YTxzM8fj ) 测试。
819
+ > [ 运行] ( https://godbolt.org/z/rqG613W94 ) 测试。
820
820
821
821
## ` new ` 、` delete ` 是线程安全的吗?
822
822
0 commit comments