在Linux环境下使用C++进行并发编程,主要有以下几种方式:
POSIX Threads是Linux下最常用的线程库。
#include <pthread.h>
void* thread_function(void* arg);
pthread_t thread_id; pthread_create(&thread_id, NULL, thread_function, (void*)arg);
pthread_join(thread_id, NULL);
#include <iostream>
#include <pthread.h>
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;
}
C++11引入了标准库线程支持,使用起来更加方便和安全。
#include <thread>
void thread_function();
std::thread t(thread_function);
t.join();
#include <iostream>
#include <thread>
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;
}
Future和Promise提供了一种更高级的并发编程方式,用于线程间的同步和数据传递。
#include <future>
std::promise<T> prom;
std::future<T> fut = prom.get_future();
prom.set_value(value);
T result = fut.get();
#include <iostream>
#include <thread>
#include <future>
void thread_function(std::promise<int> prom) {
int value = 42;
prom.set_value(value);
}
int main() {
std::promise<int> prom;
std::future<int> 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;
}
C++17引入了并行算法库,可以方便地对标准库容器进行并行操作。
#include <execution>
std::for_each(std::execution::par, container.begin(), container.end(), [](auto& elem) { /* operation */ });
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
int main() {
std::vector<int> 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;
}
选择哪种方式取决于具体的需求和项目的复杂性。