V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  A1st0n  ›  全部回复第 1 页 / 共 1 页
回复总数  4
非常有必要
2024-11-22 09:23:55 +08:00
回复了 zhmouV2 创建的主题 分享发现 DeepSeek 发布了推理模型 R1-Lite-Preview
感觉 deepseek 在代码问答还不是如 ChatGPT 免费版
2024-11-20 09:37:28 +08:00
回复了 LuckyPocketWatch 创建的主题 C++ 如何保证一个成员函数在另一个成员函数之前获得 mutex?
使用条件变量:
```
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <chrono>

class Widget {
public:
void funcA() {
std::unique_lock lock(mutex_);
std::cout << "funcA starts\n";
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟操作
std::cout << "funcA ends\n";

// 标记 A 已完成,通知等待的线程
funcA_done_ = true;
cv_.notify_one();
}

void funcB() {
// 等待 funcA 完成
std::unique_lock lock(cv_mutex_);
cv_.wait(lock, [this] { return funcA_done_; });

std::unique_lock file_lock(mutex_);
std::cout << "funcB starts\n";
std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟操作
std::cout << "funcB ends\n";
}

private:
std::mutex mutex_; // 用于文件操作的互斥锁
std::mutex cv_mutex_; // 用于条件变量的互斥锁
std::condition_variable cv_; // 条件变量
bool funcA_done_ = false; // 标志 funcA 是否已完成
};

// 封装函数
void execA(Widget* w) {
w->funcA();
}

void execB(Widget* w) {
w->funcB();
}

int main() {
Widget w;

// 使用 std::jthread
std::jthread threadA(execA, &w); // 在一个线程里执行 A 函数
std::jthread threadB(execB, &w); // 在另一个线程里执行 B 函数

return 0;
}
```
关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3455 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 19ms · UTC 04:23 · PVG 12:23 · LAX 20:23 · JFK 23:23
♥ Do have faith in what you're doing.