-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathdifferentiating_between_threads.cpp
More file actions
31 lines (26 loc) · 1.01 KB
/
differentiating_between_threads.cpp
File metadata and controls
31 lines (26 loc) · 1.01 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
// Demonstrates §3.3 of docs/multithreading.md: std::thread::id for
// per-thread bookkeeping. Both std::thread and std::jthread use the same id type.
#include <iostream>
#include <syncstream>
#include <thread>
#include <unordered_map>
#include <vector>
void sensor_loop(int sensor_id) {
// osyncstream prevents interleaved characters within a single line.
std::osyncstream(std::cout)
<< "sensor " << sensor_id
<< " running on thread " << std::this_thread::get_id() << '\n';
}
int main() {
std::cout << "main thread id: " << std::this_thread::get_id() << '\n';
// Spawn three sensor threads; remember which jthread served which sensor.
std::unordered_map<std::thread::id, int> sensor_of;
std::vector<std::jthread> threads;
for (int sensor = 0; sensor < 3; ++sensor) {
std::jthread t(sensor_loop, sensor);
sensor_of[t.get_id()] = sensor;
threads.push_back(std::move(t));
}
for (const auto &[tid, sensor] : sensor_of)
std::cout << " sensor " << sensor << " -> thread " << tid << '\n';
}