たとえば、複数のスレッドで同時に計算される作業があります。安全なマルチスレッドカウンタインクリメント
デモンストレーション目的で、作業はwhileループ内で実行されます。 1回の反復では、各スレッドは作業の独自の部分を実行し、次の反復が始まる前にカウンタを1回インクリメントする必要があります。
私の問題は、カウンタが各スレッドによって更新されることです。
これはやりたいことが比較的簡単なように思えるので、私は「ベストプラクティス」やそれを実行する一般的な方法があると推測します。
ここでは、問題を説明し、説明に役立つサンプルコードを示します。 (ブーストスレッドを使用してイム)
class someTask {
public:
int mCounter; //initialized to 0
int mTotal; //initialized to i.e. 100000
boost::mutex cntmutex;
int getCount()
{
boost::mutex::scoped_lock lock(cntmutex);
return mCount;
}
void process(int thread_id, int numThreads)
{
while (getCount() < mTotal)
{
// The main task is performed here and is divided
// into sub-tasks based on the thread_id and numThreads
// Wait for all thread to get to this point
cntmutex.lock();
mCounter++; // < ---- how to ensure this is only updated once?
cntmutex.unlock();
}
}
};
それよりももっとあります:それは、スレッドがお互いを待つことが必要でしょうか?指定された*マスター*スレッドはありませんか?あるいは何もしないで待っているスケジューラでしょうか? –
@MatthieuM ahはい、インクリメントが実行される前にすべてのスレッドがその作業を完了する必要があります。 – AlexS
あなたの編集は間違っています:与えられた変数セットへのすべてのアクセスに同じロックを使用する必要があります。したがってここではロックは1つだけ必要です。 –