里面代码会用到的头文件
#include <iostream>
#include <string>
#include <memory>
#include <thread>
#include <vector>
#include <stdlib.h>
#include <cmath>
#include <chrono>
#include <ctime>
入门例子
void mytest()
{
std::cout<<"hello"<<'\n';
}
int main()
{
std::thread t(mytest); //开启一个线程
std::cout<<"hello world\n";
t.join(); //终结线程
}
/*输出
hello world
hello
*/
-
1.上面的代码使用了
std::thread t
,这行代码创建了一个新的线程t
,并让它执行mytest函数。当这行代码执行时,mytest函数会在新创建的线程
上开始执行。主线程(即创建t的线程)
则会继续执行下一行代码。 -
2.
t.join()是一个阻塞调用
,意味着主线程会等待,直到线程t(即mytest函数)执行完毕。换句话说,t.join()
确保了mytest函数在新线程上完成执行后,主线程才会继续执行后续的代码。如果没有t.join()
,主线程可能在mytest函数完成之前结束,这可能会导致未定义的行为,因为当主线程结束时,所有其他线程都会被强制终止,即使它们还没有完成它们的任务。
利用多线程去计算