std::this_thread::yield: 当前线程放弃执行,操作系统调度另一线程继续执行。即当前线程将未使用完的“cpu时间片”让给其他线程使用,等其他线程使用完后再与其他线程一起竞争"cpu"。
std::this_thread::sleep_for: 表示当前线程休眠一段时间,休眠期间不与其他线程竞争cpu,根据线程需求,等待若干时间。
this_thread 包装了一组可以访问当前线程信息的函数
1、get_id() 获取当前线程的id。
// thread::get_id / this_thread::get_id
#include // std::cout
#include // std::thread, std::thread::id, std::this_thread::get_id
#include // std::chrono::seconds
std::thread::id main_thread_id = std::this_thread::get_id();
void is_main_thread() {
if ( main_thread_id == std::this_thread::get_id() )
std::cout << "this is the main thread.\n";
else
std::cout << "this is not the main thread.\n";
}
int main()
{
is_main_thread();
std::thread th (is_main_thread);
th.join();
}
输出结果
this is the main thread.
this is not the main thread.
2、yield()
调用线程放弃执行,回到准备状态,重新分配cpu资源。所以调用该方法后,可能执行其他线程,也可能还是执行该线程
// this_thread::yield example
#include // std::cout
#include // std::thread, std::this_thread::yield
#include // std::atomic
std::atomic ready (false);
void count1m(int id) {
while (!ready) { // wait until main() sets ready...
std::this_thread::yield();
}
for (volatile int i=0; i<1000000; i) {}
std::cout << id;
}
int main ()
{
std::thread threads[10];
std::cout << "race of 10 threads that count to 1 million:\n";
for (int i=0; i<10; i) threads[i]=std::thread(count1m,i);
ready = true; // go!
for (auto& th : threads) th.join();
std::cout << '\n';
return 0;
}
输出结果
race of 10 threads that count to 1 million...
6189370542
3、template
void sleep_until (const chrono::time_point
阻塞调用线程,一直到指定事件
// this_thread::sleep_for example
#include // std::cout
#include // std::put_time
#include // std::this_thread::sleep_until
#include // std::chrono::system_clock
#include // std::time_t, std::tm, std::localtime, std::mktime
int main()
{
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t (system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
std::cout << "current time: " << std::put_time(ptm,"%x") << '\n';
std::cout << "waiting for the next minute to begin...\n";
ptm->tm_min; ptm->tm_sec=0;
std::this_thread::sleep_until (system_clock::from_time_t (mktime(ptm)));
std::cout << std::put_time(ptm,"%x") << " reached!\n";
return 0;
}
输出结果
current time: 11:52:36
waiting for the next minute to begin...
11:53:00 reached!
4、template
void sleep_for (const chrono::duration
阻塞调用线程,一直到指定时间段后。
// this_thread::sleep_for example
#include // std::cout
#include // std::this_thread::sleep_for
#include // std::chrono::seconds
int main()
{
std::cout << "countdown:\n";
for (int i=10; i>0; --i) {
std::cout << i << '\n';
std::this_thread::sleep_for (std::chrono::seconds(1));
}
std::cout << "lift off!\n";
return 0;
}
输出结果
countdown:
10
9
8
7
6
5
4
3
2
1
lift off!