您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。