gpt4 book ai didi

c - 等待互斥锁的线程是否会在其他线程的 mutex_unlock() 之后立即获得所有权?

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:01 26 4
gpt4 key购买 nike

我有两个线程 - threadA 和 threadB。如果 B 正在等待 A 拥有的互斥量,假设它的优先级高于 A,它会在 A 解锁后立即获得所有权吗?
这不是关于当多个线程正在等待时谁获得锁的问题,而是如果一个等待线程变得可运行并是否获得处理器的问题。

从下面的测试示例来看,它似乎并不总是发生。有人可以澄清一下吗?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

//global variables
/* START = THREAD A runs, STOP = THREAD A Stops & Waits */
volatile enum { START, STOP } state = START;
pthread_cond_t condA = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *threadA()
{
int i = 0;
int j = 0;

struct sched_param p;
p.sched_priority = 16;
pthread_setschedparam(pthread_self(), SCHED_FIFO, &p);

printf("threadA created\n");
while(1)
{
printf("threadA lock requested \n");
pthread_mutex_lock(&mutex);
while (state == STOP)
{
printf("Waiting in STOP state, until some one sends START again\n");
pthread_cond_wait(&condA, &mutex);
}
printf("threadA locked mutex \n");
//do stuff - ~a few ms of work, simulated with dummy for loop
for(j=0; j<=100000000; j++)
;
i++;
printf("threadA loop cntr %d\n",i);
//printf("threadA unlock requested \n");
pthread_mutex_unlock(&mutex);
printf("threadA unlocked mutex \n");
}
fflush(stdout);
return 0;
}

void *threadB()
{

struct sched_param p;
p.sched_priority = 17;
pthread_setschedparam(pthread_self(), SCHED_FIFO, &p);

printf("threadB created\n");
do
{
/* Time to stop threadA */
printf("threadB lock requested \n");
pthread_mutex_lock(&mutex);
printf("threadB locked mutex \n");
state = STOP;
pthread_cond_signal(&condA);
//printf("threadB unlock requested \n");
pthread_mutex_unlock(&mutex);
//printf("threadB unlocked mutex \n");
}while(0);
fflush(stdout);
return 0;
}

int main(int argc, char *argv[])
{
int j = 0;

//create our threads
pthread_t a, b;

pthread_create(&a, NULL, threadA, NULL);
/* Wait for a while to make sure A is
up & running before stopping it */
for(j=0; j<=100000; j++)
;
// Now stop A
pthread_create(&b, NULL, threadB, NULL);

fflush(stdout);


pthread_join(a, NULL);
pthread_join(b,NULL);
}

我看到的典型输出如下..
线程A创建
threadA 锁请求
threadA 锁定的互斥锁
threadB 已创建
已请求线程 B 锁
threadA 循环控制 1
threadA unlocked mutex <<A 解锁了它,所以等待的 B 应该在这里接收它??
threadA 锁请求
threadA 锁定的互斥锁
threadA 循环控制 2
threadB 锁定互斥锁 <<B 终于授予所有权 !!
threadA 解锁的互斥锁
threadA 锁请求
在 STOP 状态等待,直到有人再次发送 START

最佳答案

简单地说:不,您不能以任何方式依赖哪个等待线程将获得互斥锁,甚至不能依赖等待线程将在另一个未等待的线程之前被唤醒互斥量恰好请求并获得了锁。

事实上,操作系统调度程序甚至可能更有可能允许已经运行的线程继续运行并获得锁。

关于c - 等待互斥锁的线程是否会在其他线程的 mutex_unlock() 之后立即获得所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428049/

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