如何确保执行相同功能的两个线程互斥

时间:2010-04-23 15:59:05

标签: c++ c mutex

两个线程将使用相同的func()。两个线程应该是互斥的。如何让它正常工作?

(输出应为“abcdeabcde”)

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

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

3 个答案:

答案 0 :(得分:7)

创建互斥锁?假设你正在使用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...
}

有关教程,请参阅https://computing.llnl.gov/tutorials/pthreads/#Mutexes

答案 1 :(得分:1)

  1. 在主线程中,初始化互斥锁m。
  2. 在主线程中,创建两个都以某个函数x()开始的线程。
  3. 在x()中,获取mutex m。
  4. 在x()中,调用func()。
  5. 在x()中,释放互斥锁m。

答案 2 :(得分:0)

由于您标记了此C ++,您应该知道C ++ 11包含专门用于处理锁定的标准库功能。

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]);
}