1 2 3 4 5 6 7 8 9 10 11 12 | void threadMove(void){ int a = 1; thread t( [](int* pa){ for(;;){ *pa = (*pa * 33) % 0x7fffffff; if ( ( (*pa) >> 30) & 1) break; } }, &a); thread t2 = move(t); // 改为 t2 = t 将不能编译。 t2.join(); cout << "a=" << a << endl; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | void threadSwap(void){ int a = 1; thread t( [](int* pa){ for(;;){ *pa = (*pa * 33) % 0x7fffffff; if ( ( (*pa) >> 30) & 1) break; } }, &a); thread t2; cout << "before swap: t=" << t.get_id() << ", t2=" << t2.get_id() << endl; swap(t, t2); cout << "after swap : t=" << t.get_id() << ", t2=" << t2.get_id() << endl; t2.join(); cout << "a=" << a << endl; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void threadMoveTerm(void){ int a = 1; thread t( [](int* pa){ for(;;){ *pa = (*pa * 33) % 0x7fffffff; if ( ( (*pa) >> 30) & 1) break; } }, &a); thread t2( [](){ int i = 0; for(;;)i++; } ); t2 = move(t); // 将会导致 std::terminate() cout << "should not reach here" << endl; t2.join(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class MyThread : public thread{ public: MyThread() noexcept : thread(){}; template<typename Callable, typename... Args> explicit MyThread(Callable&& func, Args&&... args) : thread( std::forward<Callable>(func), std::forward<Args>(args)...){ } ~MyThread() { thread::~thread(); } // disable copy constructors MyThread( MyThread& ) = delete; MyThread( const MyThread& ) = delete; MyThread& operator=(const MyThread&) = delete; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | void threadYield(void){ unsigned int procs = thread::hardware_concurrency(), // 获取物理线程数目 i = 0; thread* ta = new thread( [](){ struct timeval t1, t2; gettimeofday(&t1, NULL); for(int i = 0, m = 13; i < COUNT; i++, m *= 17){ this_thread::yield(); } gettimeofday(&t2, NULL); print_time(t1, t2, " with yield"); } ); thread** tb = new thread*[ procs ]; for( i = 0; i < procs; i++){ tb = new thread( [](){ struct timeval t1, t2; gettimeofday(&t1, NULL); for(int i = 0, m = 13; i < COUNT; i++, m *= 17){ do_nothing(); } gettimeofday(&t2, NULL); print_time(t1, t2, "without yield"); }); } ta->join(); delete ta; for( i = 0; i < procs; i++){ tb->join(); delete tb; }; delete tb; } |
1 2 3 4 5 6 7 8 9 | $time ./a.out without yield elapse 0.050199s without yield elapse 0.051042s without yield elapse 0.05139s without yield elapse 0.048782s with yield elapse 1.63366s real 0m1.643s user 0m1.175s sys 0m0.611s |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |