C++20增加了jthread类,该类的对象可以在析构时自动调用join:
- #include
- #include
- #include
- using namespace std;
-
- unsigned long getTimestamp()
- {
- return chrono::system_clock::now().time_since_epoch().count()/chrono::system_clock::period::den;
- }
-
- void func()
- {
- for(int i = 0; i < 5; ++i) {
- std::cout << "Thread 1 executing:" << getTimestamp() <
- std::this_thread::sleep_for(std::chrono::seconds(1));
- }
- }
-
- int main()
- {
- cout << "begin:" << getTimestamp() << endl;
- {
- jthread t1(func);
- }
- cout << "end:" << getTimestamp() << endl;
- return 0;
- }
运行程序输出:
begin:1694759618
Thread 1 executing:1694759618
Thread 1 executing:1694759619
Thread 1 executing:1694759620
Thread 1 executing:1694759621
Thread 1