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

问题描述 投票:3回答:1

在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;
}
c multithreading thread-safety c11 c17
1个回答
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 ++提供的相同工具箱,也要保持代码结构良好的原则。

© www.soinside.com 2019 - 2024. All rights reserved.