您好,登錄后才能下訂單哦!
C++ 中有多種線程模型可供選擇,具體取決于您的需求和應用程序的復雜性。以下是一些常見的 C++ 線程模型:
#include <iostream>
#include <thread>
void task() {
std::cout << "Task executed in single thread" << std::endl;
}
int main() {
std::thread t(task);
t.join();
return 0;
}
std::thread
類來創建和管理線程。#include <iostream>
#include <thread>
void task(int id) {
std::cout << "Task " << id << " executed in thread " << std::this_thread::get_id() << std::endl;
}
int main() {
const int num_threads = 4;
std::thread threads[num_threads];
for (int i = 0; i < num_threads; ++i) {
threads[i] = std::thread(task, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#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 (auto& 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 task(int id) {
std::cout << "Task " << id << " executed in thread " << std::this_thread::get_id() << std::endl;
}
int main() {
ThreadPool pool(4);
for (int i = 0; i < 8; ++i) {
pool.enqueue(task, i);
}
return 0;
}
std::async
和 std::future
,可以簡化異步編程。std::async
可以用于啟動一個異步任務,并返回一個 std::future
對象,該對象可以在適當的時候獲取任務的結果。#include <iostream>
#include <future>
int task(int id) {
std::cout << "Task " << id << " executed in thread " << std::this_thread::get_id() << std::endl;
return id * 2;
}
int main() {
std::future<int> result = std::async(task, 42);
std::cout << "Waiting for task result..." << std::endl;
int res = result.get();
std::cout << "Task result: " << res << std::endl;
return 0;
}
這些線程模型可以根據您的應用程序需求進行選擇和組合。在實際應用中,您可能需要根據具體情況調整線程數量、任務分配策略等。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。