简体   繁体   English

线程同步-编写者优先级锁定

[英]Thread synchronization - writer priority locks

So, I am using C on a unix system and have access to the pthreads & semaphore.h libraries. 因此,我在UNIX系统上使用C,并且可以访问pthreads&semaphore.h库。

Here is the problem (I believe this boils down to a "writer priority rw lock" problem): 这是问题所在(我认为这可以归结为“写入优先级读写锁”问题):

For simplicities sake, I have two different processes that a thread can run: A & B. 为简单起见,线程可以运行两个不同的进程:A和B。

B is more important than A, and thus if there is ever a B waiting to run, I do not want any more A processes to start executing until all of the B processes have run. B比A更重要,因此,如果有B等待运行,我不希望在所有B进程都运行完之后再开始执行A进程。 Additionally, while multiple A processes can run concurrently, only 1 B process can execute at a time. 此外,尽管可以同时运行多个A进程,但一次只能执行1 B进程。

The current way I am doing this (which I believe to either be wrong, inefficient, or both) is to have the B processes require a lock for their entire execution time and the A processes will acquire and immediately release the lock at the beginning of their execution. 我目前这样做的方式(我认为这是错误的,效率低下的,或两者兼而有之)是让B进程在整个执行过程中都需要一个锁,而A进程将在B的开始时获取并立即释放该锁。他们的执行。 I am also using semaphores here to allow for the multi-reader/single writer functionality. 我也在这里使用信号灯,以实现多阅读器/单写器功能。

For various reasons, the pthread_rwlock functionality is not usable on this system, so the solution can't involve them. 由于各种原因,pthread_rwlock功能在该系统上不可用,因此解决方案不能包含它们。

If A is going to immediately release the lock, but continue using whatever resource it is that you want to lock, then why do you even bother locking to begin with? 如果A要立即释放锁定,但继续使用您要锁定的任何资源,那么为什么还要从一开始就担心锁定?

You said: -Multiple A's can run simultaneously -Only one B can run at a time 您说:-多个A可以同时运行-一次只能运行一个B

I'm assuming (but correct me if I'm wrong): -B and A cannot run at the same time 我假设(但是如果我错了,请纠正我):-B和A无法同时运行

If you immediately release the lock from A then that's going to allow a B to run at the same time. 如果立即从A释放锁,则将允许B同时运行。 Am I missing anything here? 我在这里想念什么吗?

The solution: 解决方案:

Have a mechanism that gets the resource for the a threads. 有一种机制可以获取线程的资源。 That mechanism only puts a lock on the resource one time when the first A thread starts and releases it only when all A threads are gone. 该机制仅在第一个A线程启动时对资源进行一次锁定,并仅在所有A线程都消失时才释放资源。

Have a cancel token for the A threads to use that gets set to true when a B thread begins, then when all A threads have exited the B thread can begin. 为A线程使用一个取消标记,当B线程开始时将其设置为true,然后当所有A线程退出时,B线程即可开始。

The B thread obviously locks and doesn't release until it's completed. B线程显然是锁定的,直到完成才释放。

Don't forget to check the cancel token frequently enough in the A thread so that it doesn't take too long to exit when asked. 不要忘记在A线程中检查取消令牌的频率足够高,以使退出时不会花费太长时间。

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

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