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