申し訳ありませんが、このコードがここに見つかりました - http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.htmlとmutexはこのコードで説明されていましたが、私の頭の上には少し行きました。私はミューテックスの機能を理解しており、クリティカルセクションで共有変数を保護しています。ここの特徴は私を混乱させている!私の理解では、pthread_createを使って新しいスレッドを作成しています。これはfunctionCプロセスを実行しており、カウンタをインクリメントします。カウンタは保護された変数であり、両方の関数が同時に実行されているため、カウンタはmutexで保護されていないと間違った値を返します。シンプルなCコード私は理解できません - ここでmutexは何をしていますか?
これは間違いありませんか?どうもありがとう :)。
#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(0);
}
void *functionC()
{
pthread_mutex_lock(&mutex1);
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock(&mutex1);
}
これは1つの可能なシナリオですが、もう1つは 'counter 'の最終値が1であり、2が期待されていないことです。 "Counter value:1"が2回表示されてしまうことがあります。 –
真。 C言語は、++演算がアトミックかどうかを定義しません。 –