my_func
複数のスレッドを持つプログラムから呼び出すことができる関数 ( ) があります。また、この関数を同時に 2 回以上実行したくありません。私は記憶に書いているので、同時に書いてほしくありません。
void my_func()
{
// I want a line that blocks the execution if one is still pending
/* the code here */
}
my_func
複数のスレッドを持つプログラムから呼び出すことができる関数 ( ) があります。また、この関数を同時に 2 回以上実行したくありません。私は記憶に書いているので、同時に書いてほしくありません。
void my_func()
{
// I want a line that blocks the execution if one is still pending
/* the code here */
}
関数の開始時にミューテックスロックを使用し、関数から出る前にミューテックスロックを解除します
pthread_mutex_t my_func_mutex = PTHREAD_MUTEX_INITIALIZER;
void my_func()
{
pthread_mutex_lock(&my_func_mutex); // at the beginning of your function
.....
pthread_mutex_unlock(&my_func_mutex); // do not forget to unlock your mutex before going out from your function
}
必要に応じて、他の方法でそれを行うことができます。
pthread_mutex_t my_func_mutex = PTHREAD_MUTEX_INITIALIZER;
#define MY_FUNC_MACRO() \
do { \
pthread_mutex_lock(&my_func_mutex); \
my_func(); \
pthread_mutex_unlock(&my_func_mutex); \
} while(0)
void my_func()
{
.....
}
そしてあなたのコードでは、MY_FUNC_MACRO()
代わりに呼び出しますmy_func()
同じ場所への書き込み中に衝突を回避する 1 つの方法は、書き込みが順番に行われるようにすることです。これを行う 1 つの方法は、mutex を使用することです。
int a = functionThatTakesALongTime();
pthread_mutex_lock(&mymutex);
sum+=a;
pthread_mutex_unlock(&mymutex);