【线程同步】使用 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

谢谢阅读~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值