c++11 yield函数的使用

yield函数时c++11的新特性,它在std::this_thread::yield命名空间中实现,函数声明如下:

void yield() noexcept; 

其作用是当前线程“放弃”执行,让操作系统调度另一线程继续执行

比如说你的线程需要等待某个操作完成,如果你直接用一个循环不断判断这个操作是否完成就会使得这个线程占满CPU时间,这会造成资源浪费。这时候你可以判断一次操作是否完成,如果没有完成就调用yield交出时间片,过一会儿再来判断是否完成,这样这个线程占用CPU时间会大大减少。,例如:

while(!isDone()); // Bad
while(!isDone()) yield(); // Good

代码示例:

#include "stdafx.h"
#include <iostream>  
#include <chrono>  
#include <thread> 
#include <atomic>
#include <mutex>

std::mutex g_mutex;
std::atomic<bool> ready(false);

void count1m(int id) 
{
    while (!ready)// wait until main() sets ready... 
    {             
        //若线程还有没创建的,将当前线程分配的cpu时间片,让调度器安排给其他线程,
        //由于使用了yield函数,在 not Ready 情况下,避免了空循环,在一定程度上,可以提高cpu的利用率
        std::this_thread::yield();
    }

    for ( int i = 0; i < 1000000; ++i) {}

    std::lock_guard<std::mutex> lock(g_mutex);
    std::cout << "thread : "<< id << std::endl;
}

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;
}

运行结果:

参考资料:
http://www.cplusplus.com/reference/thread/this_thread/yield/

猜你喜欢

转载自blog.csdn.net/danshiming/article/details/114111044