0

次のコードはこのサイトから取得したもので、ミューテックスの使用方法を示しています。pthread_join と pthread_mutex_lock の両方を実装しています。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0;

main()
{
   int rc1, rc2;
   pthread_t thread1, thread2;

   /* Create independent threads each of which will execute functionC */

   if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc1);
   }

   if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
   {
      printf("Thread creation failed: %d\n", rc2);
   }

   /* Wait till threads are complete before main continues. Unless we  */
   /* wait we run the risk of executing an exit which will terminate   */
   /* the process and all threads before the threads have completed.   */

   pthread_join( thread1, NULL);
   pthread_join( thread2, NULL); 

   exit(EXIT_SUCCESS);
}

void *functionC()
{
   pthread_mutex_lock( &mutex1 );
   counter++;
   printf("Counter value: %d\n",counter);
   pthread_mutex_unlock( &mutex1 );
}

上記のコードをそのまま実行したところ、次の結果が得られました。

カウンター値: 1

カウンター値: 2

しかし、2 回目の実行では、「pthread_mutex_lock( &mutex1 );」を削除しました。および「pthread_mutex_unlock( &mutex1 );」. コードをコンパイルして実行しましたが、同じ結果が得られました。

今、私を混乱させているのは、ミューテックスロックがなくても同じことができるのに(pthread_joinを使用して)、なぜ上記のコードでミューテックスロックが使用されているのですか?pthread_join が最初のスレッドが終了するまで別のスレッドの実行を妨げている場合、他のスレッドがカウンター値にアクセスするのをすでに防いでいると思います。pthread_mutex_lock の目的は何ですか?

4

1 に答える 1

5

結合により、スレッド 1 とスレッド 2 が終了するまで、開始スレッドの実行 (およびプロセスの終了) が防止されます。スレッド 1 とスレッド 2の間の同期は提供されません。ミューテックスは、スレッド 2 がカウンターを変更している間、スレッド 1 がカウンターを読み取れないようにします。

ミューテックスがないと、スレッド 1 とスレッド 2 が完全に同期して実行されるという最も明白な間違いが発生する可能性があります。それぞれカウンターからゼロを読み取り、それぞれに 1 を追加し、それぞれ「カウンター値: 1」を出力します。

于 2015-10-02T17:13:14.123 に答える