线程的一些基本操作
#include<iostream>
#include<thread>
using namespace std;
#include<mutex>
mutex mt;
timed_mutex mt2;
void fun1(string str)
{
cout << str <<endl;
}
void fun2(int &a)
{
cout << a<< endl;
}
int a = 0;
void fun3()
{
for (int i = 0; i < 10000; i++)
{
mt.lock();
a++;
mt.unlock();
}
}
int main()
{
创建线程
//thread t1(fun1,"okok");
等这个子线程结束主程序才继续执行,join是阻塞的
t1.join();
主程序return后子线程后台运行
t1.detach();
//if(t1.joinable())
// t1.join();//判断是否可调用join(),如果不用可能会报错system_error,严谨的项目中会使用joiable()
/*int i = 1;
thread t1(fun2, ref(i));
t1.join();*/
/*thread t1(fun3);
thread t2(fun3);
t1.join();
t2.join();
cout << a;*/
//lock_guard自动对mt加锁,作用域结束调用析构函数时自动解锁
//lock_guard<mutex> lg(mt);
//this_thread::sleep_for(chrono::seconds(10));//休眠
//unique_lock<timed_mutex> lg(mt2,defer_lock);
//lg.try_lock_for(chrono::seconds(5));
return 0;
}
生产者消费者问题
condition_variable条件变量
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<queue>
using namespace std;
queue<int> que;
condition_variable cv;
mutex mt;
void Producer()
{
for (int i = 0; i < 10; i++)
{
{
unique_lock<mutex> lock(mt);
que.push(i);
cout << "prouce : " << i << endl;
cv.notify_one();
}
this_thread::sleep_for(chrono::microseconds(100));
}
}
void Consumer()
{
while (1)
{
unique_lock<mutex> lock(mt);
cv.wait(lock, []() {return !que.empty(); });
int v = que.front();
que.pop();
cout << "consume : " << v << endl;
}
}
int main()
{
thread t1(Producer);
thread t2(Consumer);
t1.join();
t2.join();
return 0;
}
原子变量
#include<atomic>
//原子变量,不需要再加锁,会提升效率
atomic<int> n;