スレッドを識別するには、次のことを行う必要があります
。1)そのIDを取得して保存します。
2)スレッドで実行されている関数内で、スレッドのIDを再度取得し、保存されたIDと比較します。
例:http:
//coliru.stacked-crooked.com/a/8f608dff835f96d0(プログラムはJosuttisの著書「TheC ++ Standard Library」、第2版からのものです。)
thread::id master_tid {};
/// declarations
void doSomething();
int main()
{
thread master {doSomething};
master_tid = master.get_id();
thread slave {doSomething};
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
void doSomething()
{
if (this_thread::get_id() == master_tid)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
/// ...
}
出力は次のとおりです。
master thread ...
NOT master thread ...
done
ただし、上記のスキームは、doSomething()関数の呼び出しとマスタースレッドのIDの保存の間に遅延がない場合にのみ機能します。
このような遅延が発生した場合、doSomething()関数は、実行時にマスタースレッドのIDが参照される変数にまだ保存されていないため、マスタースレッドと他の関数を区別できません。
例:http://coliru.stacked-crooked.com/a/0bff325f872ba9c2
thread::id master_tid {};
/// declarations
void doSomething();
int main()
{
thread master {doSomething};
thread slave {doSomething};
/// delay
this_thread::sleep_for(seconds {1});
master_tid = master.get_id();
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
void doSomething()
{
/// ...
}
ここで、遅延のため、出力は次のようになります。
NOT master thread ...
NOT master thread ...
done
したがって、このスキームを完全に機能させるにはどうすればよいでしょうか。メインスレッドと他のスレッドの間で通信するために条件変数を使用して、スレッドIDが保存されているかどうかを示す必要がありますか?
または、もっと簡単な方法はありますか?
すべてのスレッドは、master_tid
が割り当てられるまで待機する必要があります。sleep_for
エラーが発生しやすく、最終的にプログラムのバグにつながる手動の代わりに、同期メカニズムを使用する必要があります。すべてのスレッドが条件を待機するようにしたい場合は、条件変数を使用できます。ただし、マスターとスレーブに異なる関数を渡すか、パラメーターを渡すだけです。
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
thread::id master_tid {};
bool ready = false;
/// declarations
void doSomething() {
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
// master_tid is now assigned
if (this_thread::get_id() == master_tid)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
}
int main()
{
thread master {doSomething};
thread slave {doSomething};
{
std::lock_guard<std::mutex> lk(m);
ready = true;
master_tid = master.get_id();
}
cv.notify_all();
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加