简体   繁体   English

以只读模式线程锁定结构(C11 stdatomic)

[英]Thread-locking a structure in read only mode (C11 stdatomic)

I've created a mutex-like lock function with stdatomic that basically does 我已经用stdatomic创建了一个类似于互斥锁的锁定函数

do atomic_store(&zero, 0);
while (!atomic_compare_exchange_weak(&mystructure->address, &zero, threadlocal_address));
atomic_fetch_add(&structure->locklevel, 1);

and another unlock function that decrements locklevel and sets the address back to zero ONLY IF locklevel==0 (this allows locking before calling a function which calls another lock, allowing it to still remain locked) 以及另一个解锁函数,该函数将锁级别递减并仅在锁级别== 0的情况下将地址设置回零(这允许在调用调用另一个锁的函数之前进行锁,使其仍然保持锁定状态)

this works fine for RW locking, but I also wanted to make a R-lock function (structure can be read by multiple functions, but trying to write it [calling a RW-lock] will put it to wait) and I tried by simply using a public address instead of a threadlocal one. 这对于RW锁定效果很好,但是我还想制作一个R-lock函数(可以通过多个函数读取结构,但是尝试编写它[调用RW-lock]将使其等待),我尝试通过使用公共地址而不是线程本地地址。

The problem with this approach is it would lead to starvation of RW operations if many threads call R-lock in a loop (as locklevel would never [or hardly ever] get to zero)... any ideas? 这种方法的问题在于,如果许多线程在一个循环中调用R锁,将导致RW操作的匮乏(因为锁级别永远不会(或几乎永远不会)为零)...有什么想法吗?

You can try to use priority for read-write operations. 您可以尝试将优先级用于读写操作。 I am assuming that rw/read ratio is low in your system. 我假设rw / read比率在您的系统中较低。 Implement a basic queue for rw requests and while there is a rw request waiting in the queue, prevent read requests to acquire the lock. 为rw请求实现一个基本队列,并且当队列中有一个rw请求正在等待时,请阻止读取请求来获取锁。 After current read requests completed, acquire lock for rw and wait for it to complete. 当前的读取请求完成后,获取rw的锁定并等待其完成。 So as long as there is a rw request waiting in the queue or currently running, block read requests. 因此,只要在队列中等待或当前正在运行的rw请求,就阻止读取请求。 When rw thread unlocks and there is no more rw requests waiting in the queue allow read requests to acquire lock. 当rw线程解锁并且队列中不再有等待的rw请求时,允许读取请求获取锁定。

You may also need to use condition variables and signaling them depending on your implementation. 根据您的实现,您可能还需要使用条件变量并用信号通知它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM