How can I ensure that two threads performing the same function are mutually exclusive
3 answers
Create a mutex? Assuming you are using pthread,
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
....
void func() {
int errcode = pthread_mutex_lock(&mutex);
// deal with errcode...
// printf...
errcode = pthread_mutex_unlock(&mutex);
// deal with errcode...
}
See https://computing.llnl.gov/tutorials/pthreads/#Mutexes for a tutorial.
+7
a source to share
Since you labeled this C ++, you should be aware that C ++ 11 includes standard library functions specifically designed for locking.
std :: mutex std :: lock_guard
#include <mutex>
std::mutex arr_mutex;
char arr[] = "ABCDE";
int len = 5;
void func() {
// Scoped lock, which locks mutex and then releases lock at end of scope.
// Classic RAII object.
std::lock_guard<std::mutex> lock(arr_mutex);
for(int i = 0; i <len;i++)
printf("%c,arr[i]);
}
0
a source to share