#include<iostream>
#include<thread>
#include<atomic>//包含了很多原子类型
#include<list>
using namespace std;
/*
* C++11
* 卖票窗口 int count =100;
* lock_guard<std::mutex> guard(mtx)
* count++
* lock_guard<std::mutex> guard(mtx)
* conut--
* 互斥锁比较重,临界区代码多的事情稍稍复杂,多
* 系统理论:CAS来保证上面++--操作的原子特性就足够了,无锁操作.
* 无锁队列->是通过CAS来实现的.
*/
volatile std::atomic_bool isReady = false;
volatile std::atomic_int mycount = 0;
void funadd()
{
while (!isReady)
{
std::this_thread::yield();//线程出让当前的cpu时间片,等待下一次调度
}
for (int i = 0; i < 100; i++)
{
mycount++;
}
}
int main()
{
list<std::thread> listThread;
for (int i = 0; i < 10; i++)
{
listThread.push_back(std::thread(funadd));
}
std::this_thread::sleep_for(std::chrono::seconds(3));
isReady = true;
for (std::thread& t : listThread)
{
t.join();
}
cout << "mycount is " << mycount << endl;
return 0;
}