I would like to get the thread id associated with a known fixed integer rather than getting arbitrary id values.
#include <iostream>
#include <thread>
#include <mutex>
#include <map>
#include <vector>
using namespace std;
std::mutex mu;
std::map<std::thread::id, int> threadIDs;
void run(int i) {
std::unique_lock<mutex> map_locker(mu);
std::cout << "Thread " << threadIDs.insert(std::make_pair(std::this_thread::get_id(), i)) << endl;
map_locker.unlock();
}
int main() {
std::thread the_threads[3]; //array of threads
for (int i = 0; i < 3; i++) {
//launching the threads
the_threads[i] = std::thread(run, i);
}
for (int i = 0; i < 3; i++) {
the_threads[i].join();
}
}
For instance:
Thread ID Integer value
4 0
2 1
5 2
I get an error when running the above code:
test.cpp:14:28: error: invalid operands to binary expression ('basic_ostream >' and 'pair' (aka 'pair<__map_iterator<__tree_iterator, std::__1::__tree_node, void *> *, long> >, bool>')) std::cout << "Thread " << threadIDs.insert(std::make_pair(std::this_thread::get_id(), i)) << endl;
std::unique_lockmanually. It is designed to always unlock at the end of it's lifetime.std::unique_lockgives you. Astd::lock_guardwould be sufficient for your use.