进程和线程的区别
进程:一个在内存中运行的应用程序。每个进程都有自己独立的一块内存空间,一个进程可以有多个线程,比如在Windows系统中,一个运行的xx.exe就是一个进程。
线程:进程中的一个执行任务(控制单元),负责当前进程中程序的执行。一个进程至少有一个线程,一个进程可以运行多个线程,多个线程可共享数据。
与进程不同的是同类的多个线程共享进程的堆和方法区资源,但每个线程有自己的程序计数器、虚拟机栈和本地方法栈,所以系统在产生一个线程,或是在各个线程之间作切换工作时,负担要比进程小得多,也正因为如此,线程也被称为轻量级进程。更多
std::thread就是C++11为开发者提供的线程类。他表示一个线程,一般在构造的时候,就会启动他的线程方法。线程方法的返回值会被忽略,一般通过std::promise或者共享变量来获取。如果线程方法抛出了一场,没有被处理的话,std::terminate就会被调用。
#include
构造方法
thread() noexcept; // 默认构造方法
thread( const thread& ) = delete; // 禁用拷贝构造方法
thread( thread&& other ) noexcept; // 移动构造方法,暗示着一个thread对象只能表示一个线程,不与其他thread对象共享
// f:可调用对象;args:f的参数;如果开调用对象无法正常起启动,就会抛出异常[std::system_error](https://en.cppreference.com/w/cpp/error/system_error)
// args是采用移动或者以值的方法传递f,如果想采用引用方式需要用std::ref或者std::cref包装一下
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
例子:https://en.cppreference.com/w/cpp/thread/thread/thread
析构方法
~thread(); // 如果当前thread对象依然关联着线程,即joinable() == true, 那么就会调用std::terminate()被调用
移动赋值操作符
thread& operator=( thread&& other ) noexcept; // 如果当前thread对象依然关联着线程,即joinable() == true, 那么就会调用std::terminate()被调用
成员方法
bool joinable() const noexcept;
std::thread::id get_id() const noexcept; // 线程的唯一标识
std::thread:id是一个类,一般常用的方法有:operator==, operator<<。另外有一个特化的hash仿函数:template<> struct hashstd::thread::id; hash参考代码
native_handle_type native_handle();
static unsigned int hardware_concurrency() noexcept;
void join();
void detach();
void swap( std::thread& other ) noexcept;