百度春招一面
好像是AI应用技术部
问了C++部署自然语言处理算法的一个项目
问了一些八股
比较深度的是哈希表解决冲突的方法对应情况下删除key的情况
问了一下unorder_map的hash冲突解决,应该是基于链地址法,当时没想到
后面写题,写一个线程池,给任务队列中添加计算任务,要求实现异步获取计算结果
//线程池,执行特定任务
#include<bits/stdc++.h>
using namespace std;
class Threadpool{
public:
Threadpool(int count):thread_count(count),pool_(make_shared<Pool>()){
for(int i = 0; i < thread_count; ++i){
thread([pool = pool_](){
unique_lock<mutex> locker(pool->mtx);
while(1){
if(!pool->q.empty()){
auto task = move(pool->q.front());
pool->q.pop();
locker.unlock();
task();
cout << "111" << endl;
locker.lock();
}
else{
pool->cond.wait(locker);
}
}
}).detach();
}
}
template<class T>
void add(T&& task){
lock_guard<mutex> locker(pool_->mtx);
pool_->q.emplace(forward<T>(task));
pool_->cond.notify_one();
}
private:
struct Pool{
mutex mtx;
condition_variable cond;
queue<function<void()>> q;
};
shared_ptr<Pool> pool_;
int thread_count;
};
void sum(int a, int b){
cout << a + b << endl;
}
void test(){
Threadpool* mypool = new Threadpool(8);
mypool->add(move(bind(&sum,3,4)));
mypool->add(move(bind(&sum,2,1)));
}
int main(){
test();
return 0;
}
异步的实现应该基于future和promise或者async来实现,但自己记不清楚怎么样用了,就随便写了上面的代码。
后面复习了下async和future,实现了一下异步的
//线程池,执行特定任务
#include<bits/stdc++.h>
using namespace std;
class Threadpool{
public:
Threadpool(int count):thread_count(count),pool_(make_shared<Pool>()){
for(int i = 0; i < thread_count; ++i){
thread([pool = pool_,this](){
unique_lock<mutex> locker(pool->mtx);
while(1){
if(!pool->q.empty()){
auto task = move(pool->q.front());
pool->q.pop();
locker.unlock();
//使用async异步运行task
future<int> future = async(task);
pool->futurelist.push_back(move(future));
//task();
cout << "111" << endl;
locker.lock();
}
else{
pool->cond.wait(locker);
}
}
}).detach();
}
}
template<class T>
void add(T&& task){
lock_guard<mutex> locker(pool_->mtx);
pool_->q.emplace(forward<T>(task));
pool_->cond.notify_one();
}
struct Pool{
mutex mtx;
condition_variable cond;
queue<function<int()>> q;
//用来存每次async运行对应的future
vector<future<int>> futurelist;
};
shared_ptr<Pool> pool_;
int thread_count;
};
int sum(int a, int b){
//cout << a + b << endl;
return a+b;
}
void test(){
Threadpool* mypool = new Threadpool(8);
mypool->add(move(bind(&sum,3,4)));
mypool->add(move(bind(&sum,2,1)));
for(auto &f : mypool->pool_->futurelist){
cout << "异步运算结果为:" << f.get() << endl;
}
}
int main(){
test();
return 0;
}
阿里云工作强度 710人发布