任意のid値を取得するのではなく、既知の固定された整数に関連付けられたスレッドIDを取得したいとします。例えばthread :: idのstd :: mapを整数値に作成する
#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'で十分です。 –