Repository navigation
Expand file tree
/
Copy paththread.cpp
More file actions
58 lines (41 loc) · 1.3 KB
/
Copy paththread.cpp
File metadata and controls
58 lines (41 loc) · 1.3 KB
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
/* thread.cpp - demonstration of concurrent library */
#include <iostream>
#include <chrono>
#include <ctime>
#include <mutex>
#include <future>
using namespace std::chrono_literals;
thread_local clock_t s_clockTime;
static void syncConsoleOut(const char* text, std::ostream& handle) {
static std::mutex s_mutex;
std::lock_guard lock(s_mutex);
handle << text;
}
static void setData() {
s_clockTime = clock();
}
static clock_t readData() {
clock_t result = s_clockTime;
return result;
}
static void theThreadFunc(void* arg) {
std::promise<std::clock_t>& thePromise = *reinterpret_cast<std::promise<std::clock_t>*>(arg);
setData();
thePromise.set_value(readData());
}
int main(void) {
setData();
std::this_thread::sleep_for(1s);
std::promise<std::clock_t> thread1promise;
std::future<std::clock_t> thread1future = thread1promise.get_future();
std::thread myThread1(theThreadFunc, &thread1promise);
std::this_thread::sleep_for(1s);
std::promise<std::clock_t> thread2promise;
std::future<std::clock_t> thread2future = thread2promise.get_future();
std::thread myThread2(theThreadFunc, &thread2promise);
clock_t timer = readData();
std::cout << "Main: " << timer << " Thread1 " << thread1future.get() << " Thread2 " << thread2future.get() << std::endl;
myThread1.join();
myThread2.join();
return 0;
}