程序如下:
#include
#include
int main() {
std::thread t([](){
std::cout << "hello world." << std::endl;
});
t.join();
return 0;
}
使用thread。
更多案例:
// thread example
#include // std::cout
#include // std::thread
void foo()
{
// do stuff...
}
void bar(int x)
{
// do stuff...
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
}
不同版本c++支持语法格式有些差异,最好用c++20
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)