在 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;
}
這些方法可以組合使用,以實現更復雜的并發程序。在實際編程中,需要根據具體需求選擇合適的并發方法。