在Linux上,C++多线程的同步与异步混合使用可以通过多种方式实现。以下是一些常见的方法和技术:
互斥锁是最基本的同步机制,用于保护共享资源。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int shared_data = 0;
void thread_func() {
std::unique_lock<std::mutex> lock(mtx);
shared_data++;
lock.unlock();
}
int main() {
std::thread t1(thread_func);
std::thread t2(thread_func);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
条件变量用于线程间的同步,允许线程等待某个条件成立。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int shared_data = 0;
bool ready = false;
void producer() {
std::unique_lock<std::mutex> lock(mtx);
shared_data = 42;
ready = true;
cv.notify_one();
}
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) {
cv.wait(lock);
}
std::cout << "Shared data: " << shared_data << std::endl;
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
Boost.Asio是一个强大的异步I/O库,可以用于实现高效的异步操作。
#include <iostream>
#include <boost/asio.hpp>
#include <thread>
boost::asio::io_context io_context;
void async_operation(int id) {
std::cout << "Thread " << id << " starting asynchronous operation." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread " << id << " completing asynchronous operation." << std::endl;
}
int main() {
std::thread t1([&io_context]() { io_context.run(); });
std::thread t2([&io_context]() { io_context.run(); });
boost::asio::post(io_context, [id = 1]() { async_operation(id); });
boost::asio::post(io_context, [id = 2]() { async_operation(id); });
t1.join();
t2.join();
return 0;
}
线程池可以有效地管理线程,避免频繁创建和销毁线程的开销。
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t num_threads) : stop(false) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
template <class F, class... Args>
void enqueue(F&& f, Args&&... args) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace([f, args...] { f(args...); });
}
condition.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
void thread_func(int id) {
std::cout << "Thread " << id << " starting." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Thread " << id << " finishing." << std::endl;
}
int main() {
ThreadPool pool(2);
for (int i = 0; i < 4; ++i) {
pool.enqueue(thread_func, i);
}
return 0;
}
C++多线程的同步与异步混合使用可以通过互斥锁、条件变量、异步编程库(如Boost.Asio)和线程池等机制实现。选择合适的同步机制取决于具体的应用场景和需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。