我正在尝试了解 C++ 多线程和多个线程之间的同步。 因此,我创建了 2 个线程,第一个线程递增一个值,第二个线程递减它。我不明白为什么执行后的结果值与第一个不同,因为我从相同的值中添加和减去。
static unsigned int counter = 100;
static bool alive = true;
static Lock lock;
std::mutex mutex;
void add() {
while (alive)
{
mutex.lock();
counter += 10;
std::cout << "Counter Add = " << counter << std::endl;
mutex.unlock();
}
}
void sub() {
while (alive)
{
mutex.lock();
counter -= 10;
std::cout << "Counter Sub = " << counter<< std::endl;
mutex.unlock();
}
}
int main()
{
std::cout << "critical section value at the start " << counter << std::endl;
std::thread tAdd(add);
std::thread tSub(sub);
Sleep(1000);
alive = false;
tAdd.join();
tSub.join();
std::cout << "critical section value at the end " << counter << std::endl;
return 0;
}
输出
critical section value at the start 100
critical section value at the end 220
所以我需要的是如何保持我的值(value),我的意思是使用这两个线程计数器等于 100。
最佳答案
问题是两个线程都会进入“无限”循环 1 秒,并且它们会贪婪地使用互斥量。在两个函数中执行打印,看看哪个线程更频繁地获得锁。
互斥体用于同步对资源的访问,这样线程就不会读取/写入不完整或损坏的数据,也不会创建整齐的序列。
如果你想在执行结束时将该值保持在 100,你需要使用信号量,以便对变量进行有序的访问。
关于c++ - 使用互斥量同步线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332820/