在Linux环境下使用C++进行并发编程,主要有以下几种方式:
1. POSIX Threads (pthreads)
POSIX Threads是Linux下最常用的线程库。
基本步骤:
- 包含头文件:
#include
- 定义线程函数:
void* thread_function(void* arg);
- 创建线程:
pthread_t thread_id; pthread_create(&thread_id, NULL, thread_function, (void*)arg);
- 等待线程结束:
pthread_join(thread_id, NULL);
示例代码:
#include
#include
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return NULL;
}
int main() {
pthread_t thread_id;
if (pthread_create(&thread_id, NULL, thread_function, NULL) != 0) {
std::cerr << "Failed to create thread" << std::endl;
return 1;
}
pthread_join(thread_id, NULL);
std::cout << "Thread has finished" << std::endl;
return 0;
}
2. C++11 Standard Library Threads
C++11引入了标准库线程支持,使用起来更加方便和安全。
基本步骤:
- 包含头文件:
#include
- 定义线程函数:
void thread_function();
- 创建线程:
std::thread t(thread_function);
- 等待线程结束:
t.join();
示例代码:
#include#include void thread_function() { std::cout << "Thread is running" << std::endl; } int main() { std::thread t(thread_function); t.join(); std::cout << "Thread has finished" << std::endl; return 0; }
3. C++11 Future and Promise
Future和Promise提供了一种更高级的并发编程方式,用于线程间的同步和数据传递。
基本步骤:
- 包含头文件:
#include
- 创建Promise对象:
std::promise
prom; - 获取Future对象:
std::future
fut = prom.get_future(); - 在线程中设置值:
prom.set_value(value);
- 在主线程中获取值:
T result = fut.get();
示例代码:
#include
#include
#include
void thread_function(std::promise<int> prom) {
int value = https://www.yisu.com/ask/42;"hljs">int main() {
std::promise prom;
std::future fut = prom.get_future();
std::thread t(thread_function, std::move(prom));
t.join();
int result = fut.get();
std::cout << "Thread returned: " << result << std::endl;
return 0;
}
4. C++17 Parallel Algorithms
C++17引入了并行算法库,可以方便地对标准库容器进行并行操作。
基本步骤:
- 包含头文件:
#include
- 使用并行算法:
std::for_each(std::execution::par, container.begin(), container.end(), [](auto& elem) { /* operation */ });
示例代码:
#include#include #include #include int main() { std::vector vec = {1, 2, 3, 4, 5}; std::for_each(std::execution::par, vec.begin(), vec.end(), [](int& elem) { elem *= 2; }); for (int elem : vec) { std::cout << elem << " "; } std::cout << std::endl; return 0; }
总结
- POSIX Threads:适用于需要底层控制的场景。
- C++11 Standard Library Threads:提供了更现代和安全的线程管理。
- Future and Promise:适用于复杂的线程间通信和同步。
- Parallel Algorithms:适用于对标准库容器进行并行操作。
选择哪种方式取决于具体的需求和项目的复杂性。