gpt4 book ai didi

c++ - 锁定特定线程

转载 作者:行者123 更新时间:2023-11-28 06:39:22 24 4
gpt4 key购买 nike

如果多个线程同时尝试获取同一个互斥锁,有没有办法给某个线程优先级

例如你有两个同时启动的线程,它们休眠然后尝试获取锁

在主线程中

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_t thrd1, thrd2;
pthread_create( &thrd1, NULL, someFunc, NULL);
pthread_create( &thrd2, NULL, someFunc, NULL);

someFunc() 会有

usleep(1000);
pthread_mutex_lock(&mut);

我认为这与线程优先级有关,但这似乎是另一个主题。有没有办法保证线程 2 首先获得 mut 上的锁?

最佳答案

您的问题未明确说明,因为您没有提供有关用例的任何参数或您如何确定要做出选择。您似乎认为仅优先级就足以让您获得想要的行为,但这是一个谬论。

Priority alone is insufficient.

Priority alone does not let a higher priority thread wrest control of a mutex away from a lower priority thread that has acquired a lock. The lower priority thread must voluntarily yield the lock for the sake of safely handling the protected critical section. If the higher priority thread was allowed to yank the mutex away from the lower priority thread, the state in the critical section may be left inconsistent by the lower priority thread, and this could cause problems for the higher priority thread.

这里有一些选项。

Option 1: Start thread 2 first.

This is the simplest solution. Just launch thread 2 first, and let it notify the main thread when it has acquired the lock. Then, the main thread can start thread 1.

如果您真的只想让每个线程在没有主线程干预的情况下解决问题,那么您可以指定“保证线程 2 首先获得锁”的含义。如果线程 1 真的首先醒来,并且在没有任何争用的情况下获取锁,您希望它对此做什么?而且,线程 1 如何知道它是线程 1 而不是线程 2?

Option 2: Why care about which thread is which?

If there is no specific reason that thread 2 is thread 2, then you could just let which ever thread gets the lock first do whatever it is that thread 2 is supposed to do, and the subsequent thread does whatever thread 1 is supposed to do.

这将问题简化为只需要知道是否有任何线程已经离开。但是,如果您真的关心线程 2 应该先执行,那么您仍然需要处理线程 1 不按顺序获得锁的情况。因此,它需要以某种方式知道它是线程 1,并且需要以某种方式知道线程 2 尚未完成它的工作。

Option 3: Make thread 1 wait for thread 2 (somehow).

When the thread starts, it first determines which thread it is. If it is thread 1, it waits for an indication from thread 2 that it can acquire the lock. If it is thread 2, it first acquires the lock, then delivers an indication to thread 1 that it may acquire the lock.

选项 1 和 3 有一个线程通知另一个线程。关于如何传递此通知有很多变化。您可以使用信号量、条件等待、管道,甚至是自旋锁。还有很多其他选择,这取决于您认为什么是适合您的应用程序的正确选择。

关于c++ - 锁定特定线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com