创建thread :: id的std :: map为Integer值

时间:2017-11-20 18:46:14

标签: c++ multithreading

我想获得与已知固定整数关联的线程ID,而不是获取任意id值。

#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();
    }
}

例如:

Thread ID     Integer value
4             0
2             1
5             2

运行上面的代码时出错:

  

test.cpp:14:28:错误:二进制表达式的操作数无效(&#39; basic_ostream&gt;&#39;和             &#39;一对&#39; (又名&#39;对&lt; __ map_iterator&lt; __ tree_iterator,std :: __ 1 :: __ tree_node,void *&gt; *,long&gt;&gt;,bool&gt;&#39;))           std :: cout&lt;&lt; &#34;线程&#34; &LT;&LT; threadIDs.insert(std :: make_pair(std :: this_thread :: get_id(),i))&lt;&lt; ENDL;

1 个答案:

答案 0 :(得分:4)

std::pair无法通过ostream打印(请查看允许的类型here),因此您需要单独打印其成员:

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;

请注意,正如@FrançoisAndrieux所指出的,您不需要手动unlock unique_lock,因为它会在被破坏时自动解锁(超出范围)。

正如@JesperJuhl所说,lock_guard在这种情况下是更好的做法(它提供了您正在寻找的最低功能)。