在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++程序中实现并发编程。你可以根据自己的需求选择合适的方法。