QtExamples/ExThreadSafety/multithread.h

53 lines
1.2 KiB
C
Raw Permalink Normal View History

2022-01-20 22:15:25 +08:00
/*******************************************************************
* Copyright (C) 2022 All rights reserved.
*
* Author: <xmulitech@gmail.com>
* GitHub: https://github.com/xmuli
* Blog: https://ifmet.cn
*
* Create: 2022.01.12
* Modify: 2022.01.14
* File: multithread.h
* Description: 线线
* atomic mutex
*
******************************************************************/
#ifndef MULTITHREAD_H
#define MULTITHREAD_H
#include <atomic>
#include <mutex>
#include <thread>
#include <iostream>
using namespace std;
// 方案一:定义为原子变量 atomic
//atomic<int> g_num = 0;
// 方案二:加锁 mutex
int g_num = 0;
mutex g_mutex;
void addition()
{
for (int i = 0; i < 5000; ++i) {
g_mutex.lock(); // 尝试和下一行的 cout 行互换位置
cout << "threadId:" << this_thread::get_id() << " g_num:" << g_num << endl;
g_num++;
g_mutex.unlock();
}
}
使
int main()
{
thread th1(addition);
thread th2(addition);
th1.join();
th2.join();
cout << "g_num:" << g_num << endl;
return 0;
}
#endif