c++多线程使用
1.c++ thread
点击查看代码
#include <iostream>
#include <thread>
void M_threadFun()
{
std::cout<<"now thread begin running"<<std::endl;
for(int i=0;i<10;++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout<<"now thread should quit"<<std::endl;
}
int main()
{
//this is main thread
std::cout<<"this is in main"<<std::endl;
auto th = new std::thread(M_threadFun);
th->join();
std::cout<<"now in main"<<std::endl;
}
2.#pragma omp parallel关键字
该关键字也可以实现多线程的功能,但是需要注意:#pragma omp parallel关键字创建多线程必须在编译时加上-fopenmp选项
点击查看代码
(1)#pragma omp parallel for
for()
(2)#pragma omp parallel
{//注意:大括号必须要另起一行
#pragma omp for
for()
}