c++ - 使用互斥量同步线程

标签 c++ multithreading

我正在尝试了解 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/

相关文章:

c++ - 实现全功能的移位流语法

c++ - 为什么caffe使用#define宏来创建函数

ios - observeValueForKeyPath 总是从主线程调用吗?

c - 为什么我的线程合并排序比基本的递归合并排序慢? [复制]

Python:使用 subprocess.Popen 执行长时间运行的进程,杀死它并访问其输出

c++ - 在 win7-64 位中通过 mingw 使用 boost.python 编译一些代码

c++ - 我应该将 RAII 应用于我分配的所有数组吗?

c++ - 递归中需要双指针

multithreading - 在线程中更改/初始化的返回值

java - 管理守护线程池