Cancel request interruption
Cancel request interruption
In version 0.8.7.4, the C++ SDK introduced support for canceling request interruptions, enabling users to cancel requests actively from another thread. This document focuses on explaining how to use this feature to cancel a request:
Pre-configuration
To cancel a request, in addition to operations during request processing, the C++ SDK also requires configuring relevant variables when creating the Client and Request before processing the user request to avoid unintentionally canceling a request that wasn't meant to be canceled. The main configurations are as follows:
ClientOption: When creating a client, if you want the requests sent from this client to support request cancellation, add the following code under the client's clientOption configuration:clientOption.client_enable_cancel = true;(Here, clientOption is just an example. Please make corresponding changes according to the variable name in your own code.)Request: After creating a request, manually add the following code to modify the request attributes so that the request can support cancellation:request.set_request_cancelable(true);(Here, request is just an example. Please make corresponding changes according to the variable name in your own code.)
Request cancellation
After a cancellable request is sent and before it is processed, users can call client.cancel(*request) from another thread to cancel the request.
Simple example
Pre-configuration for client creation:
1ClientOptions option;
2option.max_parallel = 10;
3option.endpoint = "bj.bcebos.com";
4option.client_enable_cancel = true;
5std::string ak = "";
6std::string sk = "";
7Client client(ak, sk, option);
8test_cancel();
Send a cancelable request and cancel it after one second:
1void threadPutObject(Client* client, PutObjectRequest* request, PutObjectResponse* response){
2 client->put_object(*request, response);
3}
4void threadChangeCancel(Client* client, PutObjectRequest* request){
5 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
6 client->cancel_request(*request);
7}
8void test_cancel(Client& client){
9 FileInputStream file(g_object);
10 PutObjectRequest request(g_bucket, g_object, &file);
11 PutObjectResponse response;
12 request.set_request_cancelable(true);
13 std::thread t1(threadPutObject, &client, &request, &response);
14 std::thread t2(threadChangeCancel, &client, &request);
15
16 t1.join();
17 t2.join();
18}
