开发者

How can I ensure two threads executing the same function to be mutually exclusive

开发者 https://www.devze.com 2022-12-27 18:53 出处:网络
Two threads are going to use the same func(). The two threads should be mutually exclusive. How do I get it to work properly?

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.


  1. In the main thread, initialize mutex m.
  2. In the main thread, create two threads that both start in some function x().
  3. In x(), get mutex m.
  4. In x(), Call func().
  5. 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]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消