您好,登錄后才能下訂單哦!
在Linux下,C++多線程可以通過(guò)多種方式實(shí)現(xiàn)負(fù)載均衡。以下是一些常見(jiàn)的方法:
線程池是一種管理線程的機(jī)制,可以有效地分配任務(wù)給線程池中的線程,從而實(shí)現(xiàn)負(fù)載均衡。
#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;
}
任務(wù)隊(duì)列是一種將任務(wù)分配給多個(gè)線程的簡(jiǎn)單方法。每個(gè)線程從隊(duì)列中獲取任務(wù)并執(zhí)行。
#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;
}
工作竊取算法是一種動(dòng)態(tài)負(fù)載均衡策略,適用于多處理器系統(tǒng)。每個(gè)線程都有一個(gè)本地任務(wù)隊(duì)列,當(dāng)一個(gè)線程的任務(wù)隊(duì)列為空時(shí),它會(huì)嘗試從其他線程的隊(duì)列中竊取任務(wù)。
#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下實(shí)現(xiàn)C++多線程的負(fù)載均衡。選擇哪種方法取決于具體的應(yīng)用場(chǎng)景和需求。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。