在Linux環境中,C++可以通過多種方式實現并發編程。以下是一些常用的方法:
示例代碼:
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
std::cout << "Hello from thread!" << std::endl;
return nullptr;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Error creating thread: " << result << std::endl;
return 1;
}
pthread_join(thread, nullptr);
return 0;
}
示例代碼:
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(thread_function);
t.join();
return 0;
}
std::async
和std::future
,它們允許你異步地執行函數并獲取其結果。這種方式非常適合實現生產者-消費者模式或者延遲計算。示例代碼:
#include <iostream>
#include <future>
int async_function() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, async_function);
std::cout << "Waiting for the result..." << std::endl;
int value = result.get();
std::cout << "Result: " << value << std::endl;
return 0;
}
std::atomic
、std::mutex
、std::lock_guard
等),它們可以幫助你在多線程環境中安全地共享數據。示例代碼:
#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> counter(0);
void increment_counter() {
for (int i = 0; i < 1000; ++i) {
++counter;
}
}
int main() {
std::thread t1(increment_counter);
std::thread t2(increment_counter);
t1.join();
t2.join();
std::cout << "Counter: " << counter << std::endl;
return 0;
}
這些方法可以幫助你在Linux環境下的C++程序中實現并發編程。你可以根據自己的需求選擇合適的方法。