一个C++11的线程函数

一个C++11的线程函数

#include <iostream>
#include <thread>
#include <chrono>

void printNumbers() {
    for (int i = 1; i <= 100; ++i) {
        std::cout << i << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

int main() {
    std::thread t(printNumbers);
    t.join();
    return 0;
}

//g++ -std=c++11 -o program program.cpp -pthread

/*
解释:

在主函数中,我们创建了一个名为 t 的线程,该线程调用 printNumbers 函数。
printNumbers 函数负责打印数字。它使用一个循环打印数字1到100,并在每次打印后使用 std::this_thread::sleep_for 函数暂停500毫秒。
在主函数中,我们调用 t.join() 等待线程的完成,确保线程执行完毕后程序才会退出。
编译命令中的 -std=c++11 选项指定使用 C++11 标准进行编译。-o program 用于指定输出可执行文件的名称为 "program"。-pthread 选项是为了链接线程库。

请确保将源代码保存为 program.cpp,然后使用上述编译命令进行编译。成功编译后,您可以运行生成的可执行文件 program 来观察数字的打印效果。

*/

 

posted @ 2023-07-06 14:04  He_LiangLiang  阅读(4)  评论(0编辑  收藏  举报