在 Linux 中使用 C++ 编程处理并发,你可以采用以下几种方法:
<thread>
库来创建和管理线程。以下是一个简单的多线程示例:#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread t1(print_hello);
std::thread t2(print_hello);
t1.join();
t2.join();
return 0;
}
<vector>
和 <unistd.h>
库来创建和管理进程。以下是一个简单的多进程示例:#include <iostream>
#include <vector>
#include <unistd.h>
void print_hello() {
std::cout << "Hello from process " << getpid() << std::endl;
}
int main() {
std::vector<std::unique_ptr<pid_t>> processes;
for (int i = 0; i < 2; ++i) {
processes.push_back(std::make_unique<pid_t>(fork()));
}
for (auto& p : processes) {
if (*p) {
print_hello();
} else {
print_hello();
exit(0);
}
}
return 0;
}
<future>
和 <async>
库来实现异步编程。以下是一个简单的异步编程示例:#include <iostream>
#include <future>
#include <chrono>
int async_operation() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
}
int main() {
auto future = std::async(std::launch::async, async_operation);
std::cout << "Waiting for the operation to complete..." << std::endl;
int result = future.get();
std::cout << "Operation completed with result: " << result << std::endl;
return 0;
}
<mutex>
、<condition_variable>
和 <atomic>
库来实现同步原语。以下是一个简单的互斥锁示例:#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment() {
std::unique_lock<std::mutex> lock(mtx);
++counter;
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter: " << counter << std::endl;
return 0;
}
这些方法可以组合使用,以实现更复杂的并发程序。在实际编程中,需要根据具体需求选择合适的并发方法。