C++ 并行编程的方法有以下几种:
-
多线程编程:使用 C++11 标准中的 std::thread 类或 POSIX 线程库来创建多个线程,实现并行计算。
-
OpenMP:OpenMP 是一种基于共享内存的并行编程模型,可以使用 C++ 编写并行程序。OpenMP 提供了一组指令和库函数,可以在程序中标记并行区域,让编译器自动将其转换为多线程代码。
-
MPI:MPI 是一种基于消息传递的并行编程模型,可以在多台计算机之间进行并行计算。C++ 中可以使用 MPI 库来实现并行计算。
-
CUDA:CUDA 是 NVIDIA 公司开发的一种并行计算平台,可以使用 C++ 编写 GPU 加速的并行程序。
-
TBB:Intel 公司开发的 TBB(Threading Building Blocks)是一个 C++ 并行编程库,提供了一组高级的并行算法和数据结构,可以简化并行编程的复杂度。
-
OpenCL:OpenCL 是一种跨平台的并行编程框架,可以使用 C++ 编写并行程序,支持多种硬件加速器,包括 CPU、GPU、FPGA 等。
- 多线程编程
多线程编程是一种常见的并行编程方法,可以使用 C++11 标准中的 std::thread 类或 POSIX 线程库来创建多个线程,实现并行计算。
示例代码:
#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t1(hello);
std::thread t2(hello);
t1.join();
t2.join();
return 0;
}
- OpenMP
OpenMP 是一种基于共享内存的并行编程模型,可以使用 C++ 编写并行程序。OpenMP 提供了一组指令和库函数,可以在程序中标记并行区域,让编译器自动将其转换为多线程代码。
示例代码:
#include <iostream>
#include <omp.h>
int main() {
#pragma omp parallel
{
std::cout << "Hello from thread " << omp_get_thread_num() << std::endl;
}
return 0;
}
- MPI
MPI 是一种基于消息传递的并行编程模型,可以在多台计算机之间进行并行计算。C++ 中可以使用 MPI 库来实现并行计算。
示例代码:
#include <iostream>
#include <mpi.h>
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
std::cout << "Hello from process " << rank << " of " << size << std::endl;
MPI_Finalize();
return 0;
}
- CUDA
CUDA 是 NVIDIA 公司开发的一种并行计算平台,可以使用 C++ 编写 GPU 加速的并行程序。
示例代码:
#include <iostream>
#include <cuda_runtime.h>
__global__ void hello() {
printf("Hello from thread %d of block %d\n", threadIdx.x, blockIdx.x);
}
int main() {
hello<<<2, 4>>>();
cudaDeviceSynchronize();
return 0;
}
- TBB
TBB(Threading Building Blocks)是一个 C++ 并行编程库,提供了一组高级的并行算法和数据结构,可以简化并行编程的复杂度。
示例代码:
#include <iostream>
#include <tbb/parallel_for.h>
void hello(int i) {
std::cout << "Hello from thread " << i << std::endl;
}
int main() {
tbb::parallel_for(0, 4, [](int i) {
hello(i);
});
return 0;
}
- OpenCL
OpenCL 是一种跨平台的并行编程框架,可以使用 C++ 编写并行程序,支持多种硬件加速器,包括 CPU、GPU、FPGA 等。
示例代码:
#include <iostream>
#include <CL/cl.hpp>
int main() {
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
cl::Context context;
std::vector<cl::Device> devices;
for (auto platform : platforms) {
std::vector<cl::Device> platform_devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &platform_devices);
devices.insert(devices.end(), platform_devices.begin(), platform_devices.end());
}
context = cl::Context(devices);
cl::Program::Sources sources;
std::string kernel_code = "__kernel void hello() { printf(\"Hello from thread %d\\n\", get_global_id(0)); }";
sources.push_back({kernel_code.c_str(), kernel_code.length()});
cl::Program program(context, sources);
program.build(devices);
cl::CommandQueue queue(context, devices[0]);
cl::Kernel kernel(program, "hello");
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(4), cl::NullRange);
queue.finish();
return 0;
}