std::this_thread::sleep_for(休眠当前线程 sleep_for)
std::thread::detach(分离新建线程从当前线程 detach)
//std::thread;
/*default constructor Construct a thread object that does not represent any thread of execution.*/ //构造一个线程对象,并不代表任何线程执行. //thread() noexcept; //默认构造函数,不会抛出异常. //template <class Fn, class... Args> //explicit thread (Fn&& fn, Args&&... args); //构造函数. //thread (const thread&) = delete; //拷贝构造函数,被删除的(=delete); //thread (thread&& x) noexcept; //移动构造函数,不会抛出异常.
#include <iostream> #include <chrono>//std::chrono::seconds #include <thread> //thread这个头文件中包含了:class-thread, this_thread(命名空间,该命名空间中包含有几个函数: get_id, yield, sleep_until, sleep_for).
void pause_thread(const int& sec_) { std::this_thread::sleep_for(std::chrono::seconds(sec_)); //sleep_for休眠当前线程一段时间. std::cout<<"pause: "<<sec_<<std::endl; }
int main() { /*std::cout<<"countdown"<<std::endl; for(int i =10; i>0; --i){ std::cout<<i<<"\n"; std::this_thread::sleep_for(std::chrono::seconds(2)); //休眠当前线程2秒. std::cout<<"weak\n"; } std::cout<<"Lift off!\n";*/ std::cout<<"扩展3个线程并主线程分离."<<std::endl; std::thread(pause_thread, 1).detach(); std::thread(pause_thread, 2).detach(); std::thread(pause_thread, 3).detach(); std::cout<<"there is in main.\n"; std::cout<<"主线程被暂停5秒.\n"; pause_thread(5); //注意这里这里给出的主线程被暂停的时间是5秒。 //如果上面的与主线程中分离出来的线程的休眠时间小于5(<5)那么这些被分离出来的线程也会被执行完成,不然是不会被执行的. std::cout<<"-------------"<<std::endl; return 0; }
std::thread::join(把新建线程加入到当前正在执行的线程join)
#include <iostream> #include <thread> #include <chrono>
void pause_thread(const int& sec_) { std::this_thread::sleep_for(std::chrono::seconds(sec_)); std::cout<<"paused: "<<sec_<<"s\n"; }
int main() { std::cout<<"扩展线程: "<<std::endl; std::thread first_(pause_thread, 2); std::thread second_(pause_thread, 4); std::thread third_(pause_thread, 6); std::cout<<"--------------"<<std::endl; first_.join(); second_.join(); third_.join(); //新加入的线程被执行完毕才开始执行当前线程: pause_thread(1); /*auto lambda = [](){ std::cout<<"lambda"<<std::endl; }; lambda();*/ std::cout<<"--------------"<<std::endl; return 0; }