繁体   English   中英

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

[英]Create std::map of thread::id to Integer values

我想获取与已知固定整数关联的线程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:错误:对二进制表达式无效的操作数('basic_ostream>'和'pair'(aka'pair <__ map_iterator <__ tree_iterator,std :: __ 1 :: __ tree_node,void *> *,long >> ,, bool>'))std :: cout <<“线程” << threadIDs.insert(std :: make_pair(std :: this_thread :: get_id(),i))<< endl;

std::pair不能通过ostream进行打印(请在此处查看允许的类型),因此您需要单独打印其成员:

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是更好的做法(它提供了您正在寻找的最低功能)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM