0
votes

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;

1
Note that it's not necessary to unlock std::unique_lock manually. It is designed to always unlock at the end of it's lifetime. - François Andrieux
You don't actually need anything that std::unique_lock gives you. A std::lock_guard would be sufficient for your use. - Jesper Juhl

1 Answers

4
votes

std::pair can't be printed via an ostream (look at the allowed types here), so you need to print its members individually:

lock_guard<mutex> map_locker(mu);
pair<thread::id, int> p = make_pair(this_thread::get_id(), i);
threadIDs.insert(p);
cout << "Thread (" << p.first << ", " << p.second << ")" << endl;

Note that as pointed out by @FrançoisAndrieux, you don't need to manually unlock a unique_lock, as it automatically unlocks when it gets destructed (goes out of scope).

And as @JesperJuhl says, a lock_guard is better practice in this situation (it provides the minimum functionality you're looking for).