c++11 并发之旅【一】

2018-06-04  本文已影响0人  nyhoo

什么是并发

并发是指多个独立的任务同时进行。并发在我们的生活中随处可见,如:走路的时候可以打电话,一边唱歌一边跳舞,小到原子(每个核外电子同时绕着原子核高速的运转),大到宇宙各个天体按照自己的轨迹同时相互独立的运行着这些都可以看作是并发。

计算机世界的并发

并发的实现途径

C++0x线程库
///[Member functions]
//默认构造函数
thread() noexcept;
//初始化构造函数
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
//拷贝构造函数,线程对象无法被拷贝
thread(thread&) = delete;
thread(const thread&) = delete;
thread& operator=(const thread&) = delete;
//移动构造函数
thread(thread&& __t) noexcept
{ swap(__t); }
thread& operator=(thread&& __t) noexcept
{
  if (joinable())std::terminate();
  swap(__t);
  return *this;
}
//析构函数
~thread()
{if (joinable())std::terminate();}
//获得CPU核心数
static unsigned int hardware_concurrency();
//获得原生的线程标识
thread::native_handle_type native_handle();
//获得c+0x提供的线程标识
thread::id get_id() const noexcept
//交换线程状态
void swap(thread& __t) noexcept
{ std::swap(_M_id, __t._M_id); }
//whether the thread object is joinable.
bool joinable() const noexcept
{ return !(_M_id == id()); }
//The function returns when the thread execution has completed.
void join();
//分离线程让线程自己去运行
void detach();
/************************************/
//[namespace] this_thread
//Returns the thread id of the calling thread
thread::id get_id() noexcept
//是让当前线程让让出自己的CPU时间片给其他线程使用)
void yield() noexcept
//
void __sleep_for(chrono::seconds, chrono::nanoseconds);
//
template<typename _Rep, typename _Period>
void sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
//
template<typename _Clock, typename _Duration>
void sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)

开启并发世界

#include <iostream>
#include <functional>
#include <thread>
#include <string>
using namespace std;

void hello_thread(const std::string& thread_name)
{
    cout<<"["<<this_thread::get_id()<<"]-->"
        <<thread_name<<"-->"
        <<"Hello World"<<endl;
}


int main(int argc, char *argv[])
{
    thread th1,th2(hello_thread,"th2"),th3(std::move(th2));
    th1.joinable()?th1.join(),1:0;
    th2.joinable()?th2.detach(),1:0;
    th3.joinable()?th3.join(),1:0;

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读