The FFRT concurrent queue provides the capability of setting the priority and queue concurrency. Tasks in the queue can be executed on multiple threads at the same time, achieving better effect.
For example, each customer (common customer or VIP customer) submits a service request to the bank service system. The service request of the VIP customer can be processed first.
The bank system has two windows for handling service requests submitted by customers. You can use the FFRT paradigm to perform the following modeling:
The implementation code is as follows:
#include <iostream>
#include <unistd.h>
#include "ffrt/cpp/queue.h"
#include "ffrt/cpp/task.h"
class BankQueueSystem {
private:
std::unique_ptr<ffrt::queue> queue_;
public:
BankQueueSystem(const char *name, int concurrency)
{
queue_ = std::make_unique<ffrt::queue>(
ffrt::queue_concurrent, name, ffrt::queue_attr().max_concurrency(concurrency));
std::cout << "bank system has been initialized" << std::endl;
}
~BankQueueSystem()
{
queue_ = nullptr;
std::cout << "bank system has been destroyed" << std::endl;
}
// Start to queue, that is, submit queue tasks.
ffrt::task_handle Enter(const std::function<void()>& func, const char *name, ffrt_queue_priority_t level, int delay)
{
return queue_->submit_h(func, ffrt::task_attr().name(name).priority(level).delay(delay));
}
// Exit the queue, that is, cancel queue tasks.
int Exit(const ffrt::task_handle &t)
{
return queue_->cancel(t);
}
// Wait for tasks in the queue.
void Wait(const ffrt::task_handle& handle)
{
queue_->wait(handle);
}
};
void BankBusiness()
{
usleep(100 * 1000);
std::cout << "saving or withdraw ordinary customer" << std::endl;
}
void BankBusinessVIP()
{
usleep(100 * 1000);
std::cout << "saving or withdraw VIP" << std::endl;
}
int main()
{
BankQueueSystem bankQueue("Bank", 2);
bankQueue.Enter(BankBusiness, "customer1", ffrt_queue_priority_low, 0);
bankQueue.Enter(BankBusiness, "customer2", ffrt_queue_priority_low, 0);
bankQueue.Enter(BankBusiness, "customer3", ffrt_queue_priority_low, 0);
bankQueue.Enter(BankBusiness, "customer4", ffrt_queue_priority_low, 0);
// VIP customers have the priority to enjoy services.
bankQueue.Enter(BankBusinessVIP, "vip", ffrt_queue_priority_high, 0);
ffrt::task_handle handle = bankQueue.Enter(BankBusiness, "customer5", ffrt_queue_priority_low, 0);
ffrt::task_handle handleLast = bankQueue.Enter(BankBusiness, "customer6", ffrt_queue_priority_low, 0);
// Cancel the service for customer 5.
bankQueue.Exit(handle);
// Wait until all customer services are complete.
bankQueue.Wait(handleLast);
return 0;
} The main FFRT APIs involved in the preceding example are as follows:
| Name | Description |
|---|---|
| class task_attr | Task attribute class. |
| class queue_attr | Queue attribute class. |
| class queue | Queue class. |