How can I ensure two threads executing the same function to be mutually exclusive
Two threads are going to use the same func()
. The two threads should be mutually exclusive. How do I get it to work properly?
(Output should be "abcdeabcde")
char arr[] = "ABCDE";
int len = 5;
void func() 开发者_如何学C{
for(int i = 0; i <len;i++)
printf("%c",arr[i]);
}
Create a mutex? Assuming you're 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.
- In the main thread, initialize mutex m.
- In the main thread, create two threads that both start in some function x().
- In x(), get mutex m.
- In x(), Call func().
- In x(), Release mutex m.
Since you labeled this C++, you should know that C++11 includes standard library features specifically to handle 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]);
}
精彩评论