【线程同步】使用 C++ 实现 waitgroup

本文使用独占锁、原子类型、条件变量,实现线程间同步,API接口模仿Go语言中的 WaitGroup

#ifndef __WAITGROUP_H_
#define __WAITGROUP_H_

#include <mutex>
#include <atomic>
#include <condition_variable>

namespace algo {

class WaitGroup {

public:
    WaitGroup() {
        m_counter = 0;
    }

    void Add(int count = 1) {
        m_counter += count;
    }

    void Done() {
        m_counter--;
        if (m_counter.load() <= 0) {
            m_cond.notify_all();
        }
    }

    int GetCount() {
        return m_counter.load();
    }

    void Wait() {
        if (m_counter.load() <= 0) {
            return;
        }
        std::unique_lock<std::mutex> lock(m_mutex);
        m_cond.wait(lock, [&]() {
            return this->m_counter.load() <= 0;
            });
    }

private:
    std::mutex m_mutex;
    std::atomic<int> m_counter;
    std::condition_variable m_cond;
};
}

#endif

1、mutex
独占锁,用于保证同一时刻只有一个线程进入临界区

2、m_counter
原子类型,用于计数。根据 m_counter 的变化,实现多个线程间的同步

3、m_cond
条件变量,持有条件变量的线程会一直阻塞,直到被通知 或者 某一个注册的条件满足,才会解除阻塞状态

测试代码如下:
启动多个线程,并进行计数,每一个线程设置为分离状态,主线程无需等待子线程退出。
使用 waitgroup 计数后,在最外层等待所有线程结束

#include <iostream>     
#include <thread>     
#include <chrono>
#include "waitgroup.h"

using namespace algo;
using namespace std;

int main() {
	algo::WaitGroup wg;
	
	std::thread thread_list[10];
	for (int i = 0; i < 10; ++i) {
		wg.Add(1);
		thread_list[i] = std::thread([&wg, i]() {
			std::this_thread::sleep_for(std::chrono::milliseconds(10));
			std::cout << "[DEBUG] thread[" << i << "] exit" << std::endl;
			wg.Done();
			});
		thread_list[i].detach();
	}
	wg.Wait();
	std::cout << "[INFO] all thread to level" << std::endl; 
	return 0;
}

备注:因为所有子线程是同步运行的,所以打印输出是无序的

结果(每次都是随机的):

[DEBUG] thread[3] exit
[DEBUG] thread[4] exit
[DEBUG] thread[8] exit
[DEBUG] thread[5] exit
[DEBUG] thread[7] exit
[DEBUG] thread[0] exit
[DEBUG] thread[1] exit
[DEBUG] thread[2] exit
[DEBUG] thread[6] exit
[DEBUG] thread[9] exit
[INFO] all thread to level

谢谢阅读~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++ 中,可以使用多种方式实现线程同步,以下是其中的几种: 1. 互斥锁(Mutex) 互斥锁是一种最常见的线程同步机制。它可以保证同时只有一个线程可以访问共享资源,其他线程需要等待该线程释放锁之后才能访问。C++ 中可以使用 `std::mutex` 类来创建互斥锁,使用 `lock()` 和 `unlock()` 函数来加锁和解锁。 ```c++ #include <iostream> #include <thread> #include <mutex> std::mutex mtx; // 创建互斥锁 void print(int num) { mtx.lock(); // 加锁 std::cout << num << std::endl; mtx.unlock(); // 解锁 } int main() { std::thread t1(print, 1); std::thread t2(print, 2); t1.join(); t2.join(); return 0; } ``` 在这个例子中,我们创建了一个互斥锁对象 `mtx`,并在 `print()` 函数中使用 `lock()` 和 `unlock()` 函数来加锁和解锁。在 `main()` 函数中,我们创建了两个线程 `t1` 和 `t2`,同时调用 `print()` 函数并传入不同的参数。由于互斥锁的存在,两个线程会交替输出数字 1 和 2。 2. 条件变量(Condition Variable) 条件变量是一种线程同步机制,它可以让线程在某个条件满足时才继续执行。C++ 中可以使用 `std::condition_variable` 类来创建条件变量,使用 `wait()` 函数等待条件,使用 `notify_one()` 或 `notify_all()` 函数唤醒等待的线程。 ```c++ #include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; // 创建互斥锁 std::condition_variable cv; // 创建条件变量 bool ready = false; void print(int num) { std::unique_lock<std::mutex> ulock(mtx); while (!ready) cv.wait(ulock); std::cout << num << std::endl; } int main() { std::thread t1(print, 1); std::thread t2(print, 2); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> guard(mtx); ready = true; } cv.notify_all(); t1.join(); t2.join(); return 0; } ``` 在这个例子中,我们创建了一个互斥锁对象 `mtx` 和一个条件变量对象 `cv`,并在 `print()` 函数中使用了 `wait()` 函数等待条件。在 `main()` 函数中,我们创建了两个线程 `t1` 和 `t2`,并在一秒钟后唤醒两个线程。由于条件变量的存在,两个线程会等待条件满足后才会输出数字 1 和 2。 以上是两种常见的 C++ 线程同步机制,当然还有其他的同步机制,如信号量、屏障等。不同的同步机制适用于不同的场景,需要根据实际情况选择合适的机制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值