在本地C中是否有类似于std :: lock_guard的东西?

时间:2019-03-27 12:11:49

标签: c multithreading thread-safety c11 c17

在C ++中,建议使用lock_guard,因为它可以确保在销毁对象时解锁互斥体。

有没有办法在C中实现相同的功能?还是我们必须手动实现它?

互斥锁

对全局变量进行操作

解锁互斥锁

#include <stdio.h>
#include <threads.h>

long long x = 0;
mtx_t m;
static void do1()  {
   mtx_lock(&m); 
   for(int i = 0; i < 100; i++){
       x = x +1;
   }
   mtx_unlock(&m);
}

static void do2()  {
   mtx_lock(&m); 
   x = x / 3;
   mtx_unlock(&m);
}

int main(int argc, char *argv[])
{ 
   mtx_init(&m, mtx_plain);
   thrd_t thr1; 
   thrd_t thr2;
   thrd_create(&thr1, do1, 0);
   thrd_create(&thr2, do2, 0);
   thrd_join(&thr2, 0);
   thrd_join(&thr1, 0);
   return 0;
}

1 个答案:

答案 0 :(得分:5)

std::lock_guard是称为RAII的通用C ++概念的示例。 C ++程序员需要这是因为C ++函数可能会由于抛出异常而以程序员未编写自己的方式退出。

C没有例外,因此,尽管有RAII的优点和实用性,但实际上并不需要它。为了在C语言中完成这种配对动作,您需要自己调用两个函数。具体如何操作完全取决于您。例如,您可以将锁定推迟到接受回调的包装函数:

static inline void do_locked( void (*cb)(void) ) {
   mtx_lock(&m); 
   cb();
   mtx_unlock(&m);
}

static inline void do2_impl(void) {
   x = x / 3;
}

static void do2()  {
    do_locked(do2_impl);
}

即使您没有C ++所提供的相同工具箱,也只需要做纪律就可以使代码保持结构良好。

相关问题