How can I ensure that two threads performing the same function are mutually exclusive

The two threads will use the same one func()

. These two streams must be mutually exclusive. How can I get it to work correctly?

(The output should be "abcdeabcde")

char arr[] = "ABCDE";
int len = 5;

void func() {
    for(int i = 0; i <len;i++)
        printf("%c",arr[i]);
}

      

+2


a source to share


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


  • On the main thread, initialize mutex m.
  • In the main thread, create two threads that start with some function x ().
  • In x (), get mutex m.
  • In x (), calling func ().
  • In x (), release mutex m.


+1


a source


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







All Articles