2017-11-20 1 views
0

임의의 id 값을 얻는 대신 알려진 고정 된 정수와 관련된 스레드 ID를 얻고 싶습니다. 예를 들어thread :: id의 std :: map을 Integer 값으로 생성하십시오.

#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: 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;

+2

'std :: unique_lock'을 수동으로 잠금 해제 할 필요는 없습니다. 평생 동안 항상 잠금 해제되도록 설계되었습니다. –

+1

당신은 실제로'std :: unique_lock'이 당신에게주는 어떤 것도 필요하지 않습니다. 'std :: lock_guard'만으로도 충분합니다. –

답변

4
std::pairostream (허용 된 유형 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이 더 나은 방법입니다 (이 기능은 찾고있는 최소한의 기능을 제공합니다).