Skip to content

Commit

Permalink
修改格式
Browse files Browse the repository at this point in the history
  • Loading branch information
Mq-b committed May 4, 2024
1 parent b29ca64 commit eb7760c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
16 changes: 8 additions & 8 deletions md/03共享数据.md
Original file line number Diff line number Diff line change
Expand Up @@ -777,26 +777,26 @@ public:
std::recursive_mutex mtx;
void recursiveFunction(int count) {
void recursive_function(int count) {
// 递归函数,每次递归都会锁定互斥量
mtx.lock();
std::cout << "Locked by thread: " << std::this_thread::get_id() << ", count: " << count << std::endl;
if (count > 0) {
recursiveFunction(count - 1); // 递归调用
recursive_function(count - 1); // 递归调用
}
mtx.unlock(); // 解锁互斥量
}
int main() {
std::thread t1(recursiveFunction, 3);
std::thread t2(recursiveFunction, 2);
std::thread t1(recursive_function, 3);
std::thread t2(recursive_function, 2);
t1.join();
t2.join();
}
```
> [运行](https://godbolt.org/z/58z41MrxP)测试。
> [运行](https://godbolt.org/z/aefrYbGd7)测试。
- [**`lock`**](https://zh.cppreference.com/w/cpp/thread/recursive_mutex/lock):线程可以在递归互斥体上重复调用 `lock`。在线程调用 `unlock` 匹配次数后,所有权才会得到**释放**。
Expand All @@ -807,16 +807,16 @@ int main() {
同样的,我们也可以使用 `std::lock_guard`、`std::unique_lock` 帮我们管理 `std::recursive_mutex`,而非显式调用 `lock` 与 `unlock`:
```cpp
void recursiveFunction(int count) {
void recursive_function(int count) {
std::lock_guard<std::recursive_mutex>lc{ mtx };
std::cout << "Locked by thread: " << std::this_thread::get_id() << ", count: " << count << std::endl;
if (count > 0) {
recursiveFunction(count - 1);
recursive_function(count - 1);
}
}
```
> [运行](https://godbolt.org/z/6YTxzM8fj)测试。
> [运行](https://godbolt.org/z/rqG613W94)测试。
## `new``delete` 是线程安全的吗?
Expand Down
10 changes: 7 additions & 3 deletions md/04同步操作.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,9 @@ public:
}
// 从队列中弹出元素(阻塞直到队列不为空)
void pop(T& value) {
std::unique_lock<std::mutex>lk(m);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = data_queue.front();
std::unique_lock<std::mutex>lk(m);
data_cond.wait(lk, [this] {return !data_queue.empty(); });
value = data_queue.front();
data_queue.pop();
}
// 从队列中弹出元素(阻塞直到队列不为空),并返回一个指向弹出元素的 shared_ptr
Expand Down Expand Up @@ -668,3 +668,7 @@ int main() {
值:100
来自 set_exception 的异常: promise already satisfied
```

### 多个线程的等待

之前的例子中都在用 `std::future` ,不过 `std::future` 也有局限性。很多线程在等待的时候,只有一个线程能获取结果。当多个线程等待相同事件的结果时,就需要使用 `std::shared_future` 来替代 `std::future` 了。

0 comments on commit eb7760c

Please sign in to comment.