在做多线程编程时,有两个场景我们都会遇到:

今天我用一个简单的例子来给大家介绍下锁和条件变量的使用。
代码使用C++11
示例代码
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
std::mutex g_mutex; // 用到的全局锁
std::condition_variable g_cond; // 用到的条件变量
int g_i = 0;
bool g_running = true;
void ThreadFunc(int n) { // 线程执行函数
for (int i = 0; i < n; ++i) {
{
std::lock_guard<std::mutex> lock(g_mutex); // 加锁,离开{}作用域后锁释放
++g_i;
std::cout << "plus g_i by func thread " << std::this_thread::get_id() << std::endl;
}
}
std::unique_lock<std::mutex> lock(g_mutex); // 加锁
while (g_running) {
std::cout << "wait for exit" << std::endl;
g_cond.wait(lock); // wait调用后,会先释放锁,之后进入等待状态;当其它进程调用通知激活后,会再次加锁
}
std::cout << "func thread exit" << std::endl;
}
int main() {
int n = 100;
std::thread t1(ThreadFunc, n); // 创建t1线程(func thread),t1会执行`ThreadFunc`中的指令
for (int i = 0; i < n; ++i) {
{
std::lock_guard<std::mutex> lock(g_mutex);
++g_i;
std::cout << "plus g_i by main thread " << std::this_thread::get_id() << std::endl;
}
}
{
std::lock_guard<std::mutex> lock(g_mutex);
g_running = false;
g_cond.notify_one(); // 通知其它线程
}
t1.join(); // 等待线程t1结束
std::cout << "g_i = " << g_i << std::endl;
}另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。