C++11新特性
不懂就问QQ: 507143199
线程
void function_1()
{
//...
//...
}
class Factor
{
public:
void operator()(string &msg)
{
//
}
}
void main()
{
std::thread t1(function_1);
t1.join();//等待function_1执行完毕,每个线程只能被join一次
//t1.dectach();一个线一但被dectach一次就不能再被join
if (t1.joinable())
{
t1.join();
}
//或
string s = "hello world"
Factor fct;
std::thread t1(fct, std::ref(s);
//或
std::thread t1(Factor(), std::ref(s);
//输出线程id
cout << t1.get_id() << endl;
std::thread::hardware_concurrency();//可以得到当前硬件最多支持多少并发线程
}
锁
std::mutex m_mutex;
std::once_flag m_flag;
void shared_print()
{
m_mutex.lock();
//...
m_mutex.unlock();
std::lock_gard<std::mutex> locker(m_mutex);
//...出大括号后m_mutex会自动unlock
std::unique_lock<std::mutex> locker(m_mutex, std::defer_lock);
//std::defer_lock并没有锁住m_mutex
//同lock_gard一样在退出大括号后会自动解锁
locker.lock();
//...
locker.unlock();
//lock_gard不能被移动
std::unique_lock<std::mutex> locker2 = std::move(locker);
//unique_lock相较locke_gard会有部分额外性能损失
std::call_once(m_flag, [&]{ f.open("log.txt"); })
//std::call_once可以保证此方法只被执行一次
}
条件变量
std::condition_variable m_cond;
std::mutex m_mutex;
deque<int> m_q;
while(1)
{
std::unique_lock<std::mutex> locker(m_mutex);
if (m_q.empty())
{
m_cond.wait(locker);
continue;
}
//以上if还可以改造成如下:
//m_cond.wait(lokcer, [](){return !m_q.empty();})
int data = m_q.back();
m_q.pop_back();
locker.unlock();
}
//另一个线程
std::unique_lock<std::mutex> locker(m_mutex);
m_q.push_front(1);
locker.unlock();
m_cond.notify_once();//激活一个线程
m_cond.notify_all();//激活所有线程
future
#include <future>
int factorial(int n)
{
int res = 1;
return res;
}
int main()
{
std::future<int> fu = std::async(factorial, 4);
int x = fu.get();
///////////
std::promise<int> p;
std::future<int> f = p.get_future();
std::future<int> fu = std::async(std::launch::async, factorial, std::ref(f));//会创建一个子线程
p.set_value(4);
x = fu.get();
cout << "Get from child: " << x << endl;
}
thread, future和promise只能std::move不能赋值
class A
{
};
void foo(int x) {}
int main()
{
A a;
std::thread t1(a, 6);
std::thread t2(std::ref(a), 6);
std::thread t3(std::move(a), 6);
std::thread t4(A(), 6);
std::thread t5(foo, 6);
std::thread t6([](int x){return x*x;}, 6);
std::thread t7(&A::f, a, 8, 'w');
std::thread t8(&A::f, &a, 8, 'w');
}
//packaged_task
int main()
{
std::packaged_task<int()> t(std::bind(factorial, 6));
std::future<int> ret = t.get_future();
int value = ret.get();
auto t = std::bind(factorial, 6);
t();
}
时间约束
int main()
{
std::this_thead::sleep_for(chrono:milliseconds(3));
chrono::steady_clock::time_point tp = chrono::steady_clock::now() + chrono::milliseconds(4;)
std::this_thread::sleep_until(tp);
std:mutex mu;
std::unique_lock<std::mutex> locker(mu);
locker.try_lock_for(chrono::milliseconds(3));
locker.try_lock_until(tp);
std::condition_variable cond;
cond.wait_for(locker, chrono:milliseconds(3));
cond.wait_until(locker, tp);
std::promise<int> p;
std::future<int> f = p.get_future();
f.wait_for(chrono::milliseconds(3));
f.wait_until(tp);
}