gpt4 book ai didi

c++ - 使用 pthreads 作为类成员的互斥体

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:41 27 4
gpt4 key购买 nike

我有三个类,我们称它们为 A、B 和 HardwareDriver。每个类都有一个实例。 a 和 b 在两个不同的线程中运行。他们都通过 HardwareDriver 的实例访问硬件。像这样的东西:

Class A {
... };

Class B {
... };

Class HardwareDriver {
public:
int accessHardware();
};

A a;
B b;
HardwareDriver hd;
pthread_t aThread;
pthread_t bThread;

main() {
pthread_create(&aThread, NULL, &A::startA, &a);
pthread_create(&bThread, NULL, &B::startB, &b);

while (...) { };
return 0;
}

硬件不能同时被a和b访问,所以我需要用互斥量来保护代码。我是多线程的新手,但凭直觉,我会在 A 和 B 方法调用 hd.accessHardware() 方法请求硬件访问之前锁定互斥量。

现在我想知道是否有可能在 hd.accessHardware() 中执行锁定以获得更多封装。这仍然是线程安全的吗?

最佳答案

是的,你可以在你的 HardwareDriver 类中有一个互斥量,并在你的类方法中有一个关键部分。它仍然是安全的。请记住,如果您复制该对象,您还将拥有互斥体的拷贝。

关于c++ - 使用 pthreads 作为类成员的互斥体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199293/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com