-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy paththreading_example.cc
81 lines (72 loc) · 2.46 KB
/
threading_example.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Example use-case of using IPFS HTTP Client with threading.
* By: Melroy van den Berg <[email protected]>
*
* Important note: Never create multiple threads! That should NOT be needed
* in order to have parallel requests, since cURL multi API supports multiple
* simultaneous requests out-of-the-box (it's called multi API for a reason).
* However, the IPFS Client does not yet implement multiple requests in
* parallel.
*
* This single thread example is useful in application with a GUI as its main
* thread. For example with apps that are using Qt or GTK GUI toolkits.
*
* First be sure you install the IPFS client locally (as a static lib), using:
*
* mkdir build && cd build && cmake .. && make -j10 && sudo make install
*
* Then go to the example folder:
*
* cd examples
*
* Finally, build the example as follows:
*
* g++ -std=c++17 threading_example.cc -o threading_app \
/usr/local/lib/libipfs-http-client.a \
/usr/lib/x86_64-linux-gnu/libcurl.so -pthread
*
*/
#include <ipfs/client.h>
// Or when you use IPFS locally:
//#include "ipfs/client.h"
#include <iostream>
#include <sstream>
#include <thread>
void startThread() {
try {
// Create IPFS Client object, with 2 minutes time-out.
ipfs::Client client("localhost", 5001, "2m");
// Only start a single thread
std::thread thread([&client]() {
std::stringstream contents;
try {
// File should not exists, takes forever (until time-out)
client.FilesGet("QmZp1rrtGTictR2rpNcx4673R7qU9Jdr9DQ6Z7F6Wgo2bQ",
&contents);
// Code below will never be reached, since we abort the request
std::cout << "Output: " << contents.str() << std::endl;
} catch (const std::runtime_error& e) {
// Run-time error will be thrown because of the aborting request.
std::cerr << "Error: " << e.what() << std::endl;
}
});
if (thread.joinable()) {
std::cout << "Directly try to abort the request and stop the thread."
<< std::endl;
// Try to remove the Abort() and Reset() calls,
// and see the difference yourself :)
client.Abort();
thread.join(); // Should not be blocking now
client.Reset();
}
} catch (const std::exception& e) {
std::cerr << "General error: " << e.what() << std::endl;
}
}
int main() {
std::cout << "Starting thread.." << std::endl;
// Start a request inside a thread
startThread();
std::cout << "Done!" << std::endl;
return 0;
}