ExecutionQueue 提供了如下基本功能:
- 异步有序执行: 任务在另外一个单独的线程中执行, 并且执行顺序严格和提交顺序一致.
- Multi Producer: 多个线程可以同时向一个ExecutionQueue提交任务
- 支持cancel一个已经提交的任务
- 支持stop
- 支持高优任务插队
示例代码:
- 利用队列异步写文件
#include <bthread/execution_queue.h>
#include <bthread/sys_futex.h>
#include <bthread/countdown_event.h>
#include <butil/time.h>
#include <butil/fast_rand.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct LongIntTask {
long value;
string name;
};
class Hello {
public:
void start() {
bthread::ExecutionQueueOptions options;
bthread::execution_queue_start(&queue_id_, &options, print, NULL);
}
static int print(void* meta, bthread::TaskIterator<LongIntTask> &iter) {
ofstream log_file;
log_file.open("./log", ios::app);
for (; iter; ++iter) {
cout << "value:" << iter->value << ", name:" << iter->name << endl;
log_file << "value:" << iter->value << ", name:" << iter->name << "\n";
}
log_file.close();
return 0;
}
void execute() {
for (size_t i = 0; i < 10; ++i) {
LongIntTask t;
t.value = i;
t.name = "zhb";
bthread::execution_queue_execute(queue_id_, t, NULL);
}
}
void stop() {
bthread::execution_queue_stop(queue_id_);
bthread::execution_queue_join(queue_id_);
}
private:
bthread::ExecutionQueueId<LongIntTask> queue_id_;
};
int main(int argc, char const *argv[]) {
Hello hl;
hl.start();
hl.execute();
cout<< "===============" <<endl;
hl.stop();
cout<< "+++++++++++++++" <<endl;
return 0;
}
- 利用队列做累加器
#include <bthread/execution_queue.h>
#include <bthread/sys_futex.h>
#include <bthread/countdown_event.h>
#include <butil/time.h>
#include <butil/fast_rand.h>
#include <iostream>
#include <string>
using namespace std;
bool stopped = false;
struct LongIntTask {
long value;
bthread::CountdownEvent* event;
LongIntTask(long v)
: value(v), event(NULL)
{}
LongIntTask(long v, bthread::CountdownEvent* e)
: value(v), event(e)
{}
LongIntTask() : value(0), event(NULL) {}
};
int print(void* meta, bthread::TaskIterator<LongIntTask> &iter) {
stopped = iter.is_queue_stopped();
int* result = (int*)meta;
for (; iter; ++iter) {
*result += iter->value;
cout << "value:" << iter->value << endl;
if (iter->event) { iter->event->signal(); }
}
return 0;
}
int main(int argc, char const *argv[]) {
stopped = false;
bthread::ExecutionQueueId<LongIntTask> queue_id = { 0 };
bthread::ExecutionQueueOptions options;
int result;
bthread::execution_queue_start(&queue_id, &options, print, &result);
for (size_t i = 0; i < 5; ++i) {
bthread::execution_queue_execute(queue_id, i);
}
cout<< "===============" <<endl;
bthread::execution_queue_stop(queue_id);
cout<< "---------------" <<endl;
bthread::execution_queue_join(queue_id);
cout<< "result:" << result << endl;
return 0;
}