02_c++多线程_this_thread

2023-12-18 22:03:12

学习内容:this_thread中的函数

  1. get_id
  2. yield
  3. sleep_for
  4. sleep_until
this_thread

this_thread是一个类,在C++中,你可以使用this_thread命名空间提供的函数来处理线程相关的操作。它有4个功能函数,具体如下:
简介:

函数使用说明
get_idstd::this_thread::get_id()获取线程id
yieldstd::this_thread::yield()放弃线程执行,回到就绪状态
sleep_forstd::this_thread::sleep_for(std::chrono::seconds(1));暂停1秒
sleep_until如下一分钟后执行代码,如下
一分钟后执行
using std::chrono::system_clock;
std::time_t tt = system_clock::to_time_t(system_clock::now());
struct std::tm * ptm = std::localtime(&tt);
cout << "Waiting for the next minute to begin...\n";
++ptm->tm_min; //加一分钟
ptm->tm_sec = 0; //秒数设置为0//暂停执行,到下一整分执行
this_thread::sleep_until(system_clock::from_time_t(mktime(ptm)));

以下是一些常用的this_thread函数的示例用法:

  1. this_thread::sleep_for(duration)
    该函数可以让当前线程在指定的时间段内暂停执行。例如,以下代码将使当前线程睡眠1秒钟:

    #include <iostream>
    #include <thread>
    
    int main() {
        std::cout << "Start" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "End" << std::endl;
        
        return 0;
    }
    
  2. this_thread::yield()
    该函数可以让当前线程主动放弃一次CPU执行时间,以便其他线程运行。以下是一个示例:

    #include <iostream>
    #include <thread>
    
    void foo() {
        for (int i = 0; i < 5; i++) {
            std::cout << "Thread A: " << i << std::endl;
            std::this_thread::yield();
        }
    }
    
    void bar() {
        for (int i = 0; i < 5; i++) {
            std::cout << "Thread B: " << i << std::endl;
            std::this_thread::yield();
        }
    }
    
    int main() {
        std::thread t1(foo);
        std::thread t2(bar);
    
        t1.join();
        t2.join();
    
        return 0;
    }
    
  3. this_thread::get_id()
    该函数返回当前线程的唯一标识符。以下是一个示例:

    #include <iostream>
    #include <thread>
    
    void printThreadId() {
        std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
    }
    
    int main() {
        std::thread t1(printThreadId);
        std::thread t2(printThreadId);
    
        t1.join();
        t2.join();
    
        return 0;
    }
    
  4. this_thread::hardware_concurrency()
    该函数返回当前系统支持的并发线程数。以下是一个示例:

    #include <iostream>
    #include <thread>
    
    int main() {
        unsigned int numThreads = std::thread::hardware_concurrency();       
        std::cout << "Number of concurrent threads supported: " << numThreads << std::endl;
        
        return 0;
    }
    

文章来源:https://blog.csdn.net/weixin_44248637/article/details/135071406
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。