4

10 個の単純な「ワーカー」スレッドを生成する「マネージャー」スレッドを持つ単純なアプリケーションがあります。すべての「ワーカー」スレッドを同じ条件変数 (つまり、condvar) でブロックし、pthread_cond_broadcast 呼び出しで 10 個のスレッドすべてに同時にウェイクアップするように手動で信号を送りたいです。

私のアプリケーションの場合、スレッドがエラー状態になり、早期に終了する可能性があるため、10 個のスレッドすべてが同期ポイントに到達しない可能性があります。

簡単なメカニズムの 1 つは、pthread_barrier_t を作成し、10 個のスレッドすべてに pthread_barrier_wait を呼び出させることです。10 個のスレッドすべてがこの呼び出しを完了すると、すべてのスレッドが自由に実行を継続できます。ただし、これには、バリアがブロック解除するために必要なスレッドの数をスレッドが変更できる必要があります。これを安全に変更できるかどうかはわかりません。

さらに、まだ動作しているすべてのスレッドが、バリアの場合のように自動的に開始されないことを保証したいので、代わりに pthread_cond_broadcast 呼び出しを使用して手動で開始したいと考えています。ブロードキャスト呼び出しを行う前に、まだ生きているすべてのスレッド (理想的には 10 個) が condvar でブロックされていることをどのように保証しますか?

ありがとう!

4

2 に答える 2

3

以下は、条件変数と他のいくつかの変数を使用して、それを行う 1 つの方法を示しています。もっと良い方法があるかもしれませんが。コメントは、それがどのように機能するかを示す必要があります。もちろん、実際の状況に合わせて変更する必要があります。たとえば、ループが含まれている可能性があります。

int activeThreads = 0;   /* number of threads currently going */
int waitingThreads = 0;  /* number of threads waiting on the condition */
int readyFlag = 0;       /* flag to tell the threads to proceed when signaled */
pthread_cond_t  cond;    /* condition to wait on / signal */
pthread_mutex_t mtx;     /* mutex for the above */

pthread_cond_t  condWaiting; /* EDIT: additional condition variable to signal 
                              * when each thread starts waiting */

void *threadFunc(void *arg)
{
  /* Edit: Rather than incrementing 'activeThreads' here, it should be done
   * in the main thread when each thread is created (to avoid a race) */

  /* ...do stuff... */

  /* When the threads should wait, do this (they wait for 'readyFlag' to be 
   * set, but also adjust the waiting thread count so the main thread can
   * determine whether to broadcast) */
  pthread_mutex_lock(&mtx);
    if (readyFlag == 0) {
      waitingThreads++;
      do {
        pthread_cond_signal(&condWaiting); /* EDIT: signal the main thread when
                                            * a thread begins waiting */
        pthread_cond_wait(&cond,&mtx);
      } while (readyFlag == 0);
      waitingThreads--;
    }
  pthread_mutex_unlock(&mtx);

  /* ...more stuff... */

  /* When threads terminate, they decrement the active thread count */
  pthread_mutex_lock(&mtx);
    activeThreads--;
    pthread_cond_signal(&condWaiting); /* EDIT: also signal the main thread
                                        * when a thread exits to make it 
                                        * recheck the waiting thread count if
                                        * waiting for all threads to wait */
  pthread_mutex_unlock(&mtx);

  return NULL;
}

int main(int argc, char *argv[])
{
  /* Edit: Showing some code to initialize the mutex, condition variable(s),
   * etc., and create some threads -- modify as needed */
  pthread_mutex_init(&mtx,NULL);
  pthread_cond_init(&cond,NULL);
  pthread_cond_init(&condWaiting,NULL); /* EDIT: if main thread should block
                                         * until all threads are waiting */
  activeThreads = waitingThreads = readyFlag = 0;

  /* Edit: Increment 'activeThreads' here rather than in the thread function,
   * to avoid a race (if the main thread started waiting for the others
   * when not all had incremented the count yet, the main thread might end
   * up waiting for fewer threads to be ready -- though it's unlikely */
  #define NUM_THREADS 10
  pthread_t workers[NUM_THREADS];
  for (int i = 0; i < NUM_THREADS; i++) {
    /* should use appropriate thread attributes */
    if (pthread_create(&workers[i],NULL,threadFunc,NULL) == 0)
      activeThreads++;
  }

  /* ...do stuff... */

  /* Set 'readyFlag' and do condition broadcast IF all threads are waiting,
   * or just carry on if they aren't */
  pthread_mutex_lock(&mtx);
    if ((activeThreads != 0) && (activeThreads == waitingThreads)) {
      readyFlag = 1;
      pthread_cond_broadcast(&cond);
    }
  pthread_mutex_unlock(&mtx);

  /* EDIT: OR.. to wait until all threads are waiting and then broadcast, do 
   * this instead: */
  pthread_mutex_lock(&mtx);
    while (waitingThreads < activeThreads) { /* wait on 'condWaiting' until all
                                              * active threads are waiting */
      pthread_cond_wait(&condWaiting,&mtx);
    }
    if (waitingThreads != 0) {
      readyFlag = 1;
      pthread_cond_broadcast(&cond);
    }
  pthread_mutex_unlock(&mtx);

  /* ...more stuff... */

  /* If needed, you can clear the flag when NO threads are waiting.. */
  pthread_mutex_lock(&mtx);
    if (waitingThreads == 0)
      readyFlag = 0;
  pthread_mutex_unlock(&mtx);

  /* ...even more stuff... */

  return 0;
}

ただし、より簡単な方法でリソースを保護するだけでなく、これを行う正当な理由があるかどうかはわかりません。

編集: すべてのワーカーの準備が整うのをメイン スレッドが待機できるようにするために使用される 2 番目の条件変数を示す、コードにいくつかのものを追加しました。変更部分はコメントで「EDIT:」とマークされており、必要がなければ省略できます。また、インクリメントをactiveThreadsスレッド関数の外に移動することで競合状態を修正し、ミューテックスなどの初期化を示しました (エラー処理なし)。

于 2012-01-17T21:46:45.543 に答える
1

一般的に言えば、作業の準備が整ったら、条件変数 (およびそれに関連付けられたフラグ) を設定するだけです。通常、条件変数でスレッドがブロックされるのを待つ必要はありません。彼らが「遅れている」場合、フラグがすでに設定されていることに気付くだけで、ブロックする必要はありません。

しかし、すべてのワーカー スレッドが条件 var でクロークするポイントになるまで本当に待つ必要がある場合は、条件変数の組み合わせを使用できます。彼らが仕事を始めるきっかけになります。いくつかの擬似コード:

// manager thread thread

pthread_cond_t pseudo_barrier;
pthread_cond_t pseudo_barrier_complete_cond;
pthread_mutex_t pseudo_barrier_mux;
int pseudo_barrier_counter = NUM_THREADS;
int pseudo_barrier_complete_flag = 0;

void thread_manager(void) 
{
    pthread_cond_init( &pseudo_barrier, NULL);
    pthread_cond_init( &pseudo_barrier_complete_cond, NULL);
    pthread_mutex_init( &pseudo_barrier_mux, NULL);


    for (int i = 0 ; i < NUM_THREADS; ++i) {
        pthread_create( /*... */);
    }

    // wait for threads to 'stage'
    pthread_mutex_lock( &pseudo_barrier_mux);
    while (pseudo_barrier_counter != 0) {
        pthread_cond_wait( &pseudo_barrier, &pseudo_barrier_mux);
    }
    pthread_mutex_unlock( &pseudo_barrier_mux);


    // at this point, all threads have either bailed out or are waiting to go
    // let 'em rip

    pthread_mutex_lock( &pseudo_barrier_mux);
    pseudo_barrier_complete_flag = 1;
    pthread_mutex_unlock( &pseudo_barrier_mux);
    pthread_cond_broadcast( &pseudo_barrier_complete_cond);

    // do whatever else the manager thread needs to do...
}


// worker threads
void* worker_thread(void* context)
{
    int error_result = 0;

    // whatever initialization...
    //  if this thread is going to bail out due to an error, it needs to 
    //  set the `error_result` value appropriately and still drop into the 
    //  following code

    // let the manager know that this thread is waiting (or isn't going to participate)
    pthread_mutex_lock( &pseudo_barrier_mux);
    --pseudo_barrier_counter;

    if (pseudo_barrier_counter == 0) {
        // all other threads are accounted for, let the manager know we're ready
        pthread_cond_signal( &pseudo_barrier);
    }

    // if this thread isn't going to contine because of some error, it's already 
    //  accounted for that fact in the `my_barrier_count`, so we can return here
    //  without preventing the pseudo-barrier from being met.
    if (some_error_occurred) {
        pthread_mutex_lock( &pseudo_barrier_mux);
        return NULL;
    }

    // NOTE: we're still holding pseudo_barrier_mux, so the master thread is still 
    //  blocked, even if we've signaled it - it'll jhave to wait until this 
    //  thread is blocking on `pseudo_barrier_complete_cond`

    while (!pseudo_barrier_complete_flag) {
        pthread_cond_wait( &pseudo_barrier_complete_cond, &pseudo_barrier_mux);
    }
    pthread_mutex_unlock( &pseudo_barrier_mux);


    // do the work...
}

もちろん、提示された疑似コードは、実際の使用 (エラー処理を含む) のためにクリーンアップする必要があります。おそらく、サポートされているすべての条件変数、ミューテックス、およびフラグを構造体にパッケージ化します。

于 2012-01-17T22:29:34.237 に答える