c++11 并发之旅【一】

什么是并发

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

计算机世界的并发

  • 【单核CPU】单核系统上的并发并非真正物理结构的并发,它是通过在核心cpu上切换多个任务达到并发的假象让人以为两个应用或者任务在同时进行,但是实际上他是通过时间切片在短时间内进行任务切换的。

  • 【多核CPU】相比于单核系统多核系统实现了真正物理意义上面的并发,不同的应用或者任务可以被分到不同CPU上去完成。

并发的实现途径

  • 【多进程】操作系统提供了进程间的保护操作和通讯机制,可以比线程更容易的编写安全的并发代码。并且可以运行在同一台机器或者不同的机器上面。利用网络使得这种并发的可用性和可行性有很大的用处。

  • 【多线程】相比于多进程线程是轻量级的,不需要想进程那样要在启动的时候占据额外的开销。并且线程中全局数据仍然是全局的,这使得线程间通讯很容易,但这就得程序员自己管理这种共享,来避免出现不必要的冲突和歧义。

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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,748评论 8 265
  • 必备的理论基础 1.操作系统作用: 隐藏丑陋复杂的硬件接口,提供良好的抽象接口。 管理调度进程,并将多个进程对硬件...
    drfung阅读 3,620评论 0 5
  • 余永红又搅扰你了。 现在想来99年怎么会到都昌,可能命运就是让我遇到你。没恋爱,却尝到了失恋的滋味。我对你...
    搞定自己阅读 139评论 0 0
  • 大概,我是个没人要的孩子。 中午在食堂,夹起菜。我却突然想起来,自己小时候偷偷吃辣条买方便面吃的时光。可能,那是最...
    苍穹听雨阅读 703评论 0 3
  • 时间啊!时间!你为什么过得那么快! 身在2O17的我,一眨眼又快到新的一年! 时间啊!时间!多希望你能走慢点! 因...
    璃子沫阅读 373评论 0 0