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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。