您好,登錄后才能下訂單哦!
在Linux下,C++多線程可以通過多種方式實現負載均衡。以下是一些常見的方法:
線程池是一種管理線程的機制,可以有效地分配任務給線程池中的線程,從而實現負載均衡。
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
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(queueMutex);
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(queueMutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([f, args...] { f(args...); });
}
condition.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
void worker(int id) {
std::cout << "Worker " << id << " started\n";
// Simulate work
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Worker " << id << " finished\n";
}
int main() {
ThreadPool pool(4);
for (int i = 0; i < 10; ++i) {
pool.enqueue(worker, i);
}
return 0;
}
任務隊列是一種將任務分配給多個線程的簡單方法。每個線程從隊列中獲取任務并執行。
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class TaskQueue {
public:
void push(std::function<void()> task) {
std::lock_guard<std::mutex> lock(mutex);
tasks.push(task);
condition.notify_one();
}
std::function<void()> pop() {
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, [this] { return !tasks.empty(); });
auto task = tasks.front();
tasks.pop();
return task;
}
private:
std::queue<std::function<void()>> tasks;
std::mutex mutex;
std::condition_variable condition;
};
void worker(TaskQueue& queue) {
while (true) {
auto task = queue.pop();
if (task == nullptr) {
break;
}
task();
}
}
int main() {
TaskQueue queue;
std::vector<std::thread> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back(worker, std::ref(queue));
}
for (int i = 0; i < 10; ++i) {
queue.push([i] { std::cout << "Task "<< i << " started\n"; });
}
for (auto& worker : workers) {
worker.join();
}
return 0;
}
工作竊取算法是一種動態負載均衡策略,適用于多處理器系統。每個線程都有一個本地任務隊列,當一個線程的任務隊列為空時,它會嘗試從其他線程的隊列中竊取任務。
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class Worker {
public:
Worker(int id, TaskQueue& globalQueue) : id(id), globalQueue(globalQueue) {}
void run() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] { return !tasks.empty() || globalQueue.empty(); });
if (globalQueue.empty() && tasks.empty()) {
return;
}
if (!globalQueue.empty()) {
task = std::move(globalQueue.front());
globalQueue.pop();
} else {
task = std::move(tasks.front());
tasks.pop();
}
}
task();
}
}
void addTask(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(queueMutex);
tasks.push(task);
}
condition.notify_one();
}
private:
int id;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
TaskQueue& globalQueue;
};
int main() {
TaskQueue globalQueue;
std::vector<Worker> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back(i, std::ref(globalQueue));
}
for (int i = 0; i < 10; ++i) {
globalQueue.push([i] { std::cout << "Task "<< i << " started\n"; });
}
for (auto& worker : workers) {
worker.run();
}
return 0;
}
這些方法都可以在Linux下實現C++多線程的負載均衡。選擇哪種方法取決于具體的應用場景和需求。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。