임의의 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;
'std :: unique_lock'을 수동으로 잠금 해제 할 필요는 없습니다. 평생 동안 항상 잠금 해제되도록 설계되었습니다. –
당신은 실제로'std :: unique_lock'이 당신에게주는 어떤 것도 필요하지 않습니다. 'std :: lock_guard'만으로도 충분합니다. –