原生C中有没有类似于std::lock_guard的东西?

Is there something that resembles std::lock_guard in native C?

在 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;
}

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++ 提供的相同工具箱。