gpt4 book ai didi

c++ - 多个线程可以读取同一个类成员变量吗?

转载 作者:行者123 更新时间:2023-12-02 03:30:04 24 4
gpt4 key购买 nike

多个线程可以安全地读取同一个类成员变量而不创建竞争条件吗?

class foo {
int x;
};

void Thread1(foo* bar) {
float j = bar->x * 5;
}

void Thread2(foo* bar) {
float k = bar->x / 5;
}

例如,如果我们有两个线程运行 Thread1Thread2。如果每个线程都传递相同 foo 对象,它们是否可以独立运行,而不会出现竞争条件,因为我们只读取变量而不写入变量?或者访问该对象的行为是否会使整个事情变得不安全?

如果上述安全的,那么第三个线程可以安全地写入同一个foo对象,只要它不接触foo::x

#include <thread>

class foo {
public:
int x = 1;
int y = 1;
};

void Thread1(foo* bar) {
int j;
for (int i = 0; i < 1000; i++) {
j = bar->x * 5;
}
printf("T1 - %i\n", j);
}

void Thread2(foo* bar) {
int k;
for (int i = 0; i < 1000; i++) {
k = bar->x / 5;
}
printf("T2 - %i\n", k);
}

void Thread3(foo* bar) {
for (int i = 0; i < 1000; i++) {
bar->y += 3;
}
printf("T3 - %i\n", bar->y);
}

int main() {
foo bar;

std::thread t1(Thread1, &bar);
std::thread t2(Thread2, &bar);
std::thread t3(Thread3, &bar);

t1.join();
t2.join();
t3.join();

printf("x %i, y %i\n", bar.x, bar.y);

return 0;
}

最佳答案

Can multiple threads safely read the same class member variable without creating a race condition?

是和否。

- 您提供的代码不会导致竞争条件,因为当您有至少 2 个线程在同一共享资源上工作并且其中至少一个线程正在写入时,可能会出现竞争条件到该资源。

- 您的代码不被认为是线程安全的,因为它公开了 x 和 y 成员以供读取和写入,并使其成为可能(对于您或使用您的其他程序员来说)代码)导致竞争条件。您依赖于您的知识(随着时间的推移您可能会忘记)x 只能被读取而不能写入,并且 y 只能由单个线程写入。您应该通过创建 mutual exclusion 来强制执行此操作在 critical code sections .

如果您希望线程仅读取 x 和 y,则应该将此类设为 immutable .

关于c++ - 多个线程可以读取同一个类成员变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191339/

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