多线程并发同步代码:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
void Fun_1(); //声明分支线程函数 Fun_1()
void Fun_2(); //声明分支线程函数 Fun_2()
unsigned int counter = 0; //定义变量 counter,通过变量 counter 的变化来观察
线程同步情况
std::mutex mtx; //定义 mutex 类的对象 mtx 构造互斥元,互斥占有一个变量,
一段时间内仅一个线程可以访问
int main()
{
std::thread thrd_1(Fun_1); //创建线程 thrd_1,thrd_1 调用函数 Fun_1
std::thread thrd_2(Fun_2); //创建线程 thrd_2,thrd_2 调用函数 Fun_2
thrd_1.join(); //join()函数启动子线程而阻塞主线程,子线程会按照开启的先后顺
序同步运行,当子线程运行结束后,才会继续运行主线程
thrd_2.join(); //启动线程 thrd_2,并且阻塞主线程,等到线程 thrd_2 运行结束后,
再继续运行主线程;
cout<<"counter= "<< counter <<endl;
return 0;
}
void Fun_1()
{
while (true)
{
/*std::lock_guard 类 模 板 , 用 于 自 动 锁 定 解 锁 , 直 到 对 象 作 用 域 结 束 。 在
lock_guard 对象构造时,传入的 mutex 对象 mtx 会被当前线程锁住。在 lock_guard
对象被析构时,它所管理的 mutex 对象 mtx 会自动解锁*/
std::lock_guard<std::mutex> mtx_locker(mtx);
counter++;
if (counter < 20)
cout << "Function 1 counting ! counter=" << counter << endl;
else
break;
}
}
void Fun_2()
{
评论1