如何解决当一个线程不断从内存中查询变量而另一个线程对其进行更新时,是否存在竞争条件?
我有以下代码
#include <stdio.h>
#include <thread>
#include <mutex>
class A
{
public:
A(int n) : num_workers(n) {
counter_lock = new std::mutex();
threads = new std::thread[num_workers];
for (int i = 0; i < num_workers; i++) {
threads[i] = std::thread(&A::run,this);
}
}
~A() {
delete counter_lock;
}
void start() {
go = true;
counter = 0;
total = 1000000;
while (counter < total) {};
for (int i = 0; i < num_workers; i++) {
threads[i].join();
}
}
void run() {
printf("Spinning\n");
while(1) {
if (go) {
int i;
counter_lock->lock();
i = counter++;
counter_lock->unlock();
if (i >= total) break;
}
}
printf("Done\n");
}
private:
std::mutex* counter_lock;
std::thread* threads;
int num_workers;
int counter;
int total;
bool active;
bool go;
};
int main() {
A a = A(10);
a.start();
}
在A
的构造函数中,我创建一个num_workers
的线程池。他们都在执行一个函数A::run
,该函数只是等待直到收到go
的信号,然后开始递增counter
。函数start
旨在与调用它的任何人同步,因此在这种情况下,它应与main
同步。因此,在向所有工作线程发出counter
信号之后,它只是闲置直到total
到达go
。
该代码按预期工作。 counter
最终以10000010
结尾,这是有道理的,因为每个10
线程在退出前已经对counter
进行了一次递增。
我是否没有注意到比赛条件?我在counter
循环中读取while(counter < total) {}
时没有锁定,这是否会导致任何问题呢?
谢谢您的建议。
编辑:我用以下(也许是线程安全的)实现替换了while (counter < total) {}
循环。但是,由于counter
的值尚未更新,它仍然永远循环永远。
while (1) {
int c;
counter_lock->lock();
c = counter;
counter_lock->unlock();
if (c >= total) break;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。