C++多线程编程中std::future的使用

更新时间:2023-06-05 01:51:33 阅读: 评论:0

C++多线程编程中std::future的使⽤
最近⼀直在搞多线程,C++的底⼦较烂,⼀开始直接⽤.detach()⽅法创建线程,但⽆法使输⼊顺序和输出顺序同步,⽽且输⼊数据在不断的产⽣,类似⽣产者和消费者问题,不断的创建新线程会浪费时间和资源,所以想到⽤线程池的⽅法。
我理解这段话的意思就是因为多线程输出没办法控制输出的顺序,那么future就为所有会有输出的位置放⼀个占位符,认定这个位置会有⼀个输出,但是具体什么时间会有不确定。
测试结果:
GitHub2k多star的⼀个线程池的项⽬,改了⼀下example,看输出更直观⼀些。日语翻译中文
话说昨天有个⼩破站的后台源码被push上来了,golang的教程可能要⽕了,push⼀时爽,牢饭吃到⽼,职业道德还是要有的。
hello hello hello hello hello hello hello hello hello hello 1201220100 world
dime
短篇英语故事1world 2  world 0 world 1 hello 2 world 2 world 2 hello 0 hello 3 world 0 world 0 hello 1
hello 3 hello 0 hello 1 hello 2 world 0 world 1 hello 1 hello 2 world 2 world 0 hello 3
world 3 world 1 world 3 world 0world 1  world 2 world 2 world 1 world 3
012012012012301230123
可以发现,创建了10个线程,线程的执⾏是并⾏的,但是输出的结果和输出的顺序是⼀样的。
完整代码:
//*****************ThreadPool.h**********************
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include<vector>
#include<queue>
#include<memory>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<future>
#include<functional>
#include<stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<)>::type>;
~
ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()>> tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
不寒而栗是什么意思/
/ the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
:stop(fal)
{
{
for(size_t i =0;i<threads;++i)
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex>lock(this->queue_mutex);                        this->condition.wait(lock,
[this]{return this->stop ||!this-&pty();});
if(this->stop && this-&pty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
practid
task();
}
}
);
}
// add new work item to the pool
template<class F, Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<)>::type>
{
using return_type = typename std::result_of<)>::type;
auto task = std::make_shared< std::packaged_task<return_type()>>(            std::bind(std::forward<F>(f), std::forward<Args>(args)...) );
std::future<return_type> res = task->get_future();
nieche
{
std::unique_lock<std::mutex>lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
}
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex>lock(queue_mutex);
stop = true;
}
for(std::thread &worker: workers)
worker.join();
}
#endif
/
bowen/*****************example.cpp**********************
#include<iostream>
#include<vector>
#include<chrono>
#include"ThreadPool.h"
std::vector<std::vector<int>> a;
dead beat
int main()
{
ThreadPool pool(10);
//create a <future> vector to wait the output
std::vector< std::future<std::vector<int>>> results;
std::vector<int> batch ={3,3,3};
韩剧坏男人结局
int m =3;
for(int b =0; b < batch.size(); b++)
规格英文{
if(m >0){
batch.push_back(4);
}
for(int i =0; i < batch[b]; i++)
{
std::vector<int> res ={i};
std::cout <<"hello "<< i <<" ";
std::this_thread::sleep_for(std::chrono::conds(1));                    std::cout <<"world "<< i <<" ";
return res;
}));
}
m--;
}
//get output
for(auto&& result: results)
std::cout << std::endl;
std::cout << std::endl;
//after get all output, print it
for(int i =0; i < a.size(); i++)
{
for(int j =0; j < a[i].size(); j++)
std::cout << a[i][j]<<" ";
}
system("pau");
return0;
}

本文发布于:2023-06-05 01:51:33,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/134294.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:输出   线程   顺序   创建
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图