所以我正在开发一个linux内核模块,它需要在kthread启动的单独线程中进行无限等待循环。以下是kthread运行的函数,train.queue_mutex是在kthread之前初始化的互斥锁(通过mutex_init(& train.queue_mutex))
我不能为我的生活找出它为什么锁定内核。我的想法是,在每次迭代的mdelay和schedule()之间,其他进程应该获得CPU时间。
int train_thread(void *param)
{
while (!train.is_deactivating)
{
mutex_lock_interruptible(&train.queue_mutex);
while (train.num_waiting > 0)
{
int five_foward = (train.stop + 5) % 10;
int five_back = (train.stop - 5) % 10;
int i = train.stop;
int max_count = 0;
int max_count_index = 0;
for (;i != five_foward; i = (i + 1) % 10)
{
int count = robots_count(train.waiting[i]);
if (count > max_count)
{
max_count_index = i;
max_count = count;
}
}
for (i = train.stop ;i != five_back; i = (i - 1) % 10)
{
int count = robots_count(train.waiting[i]);
if (count > max_count)
{
max_count_index = i;
max_count = count;
}
}
// Should have max_count_index set to index of stop with the most bots
printk("Most bots %d at stop %d\n", max_count, max_count_index);
mutex_unlock(&train.queue_mutex);
schedule();
mutex_lock_interruptible(&train.queue_mutex);
}
mutex_unlock(&train.queue_mutex);
mdelay(10);
}
train.is_active = 0;
return 0;
}
答案 0 :(得分:1)
for (i = train.stop ;i != five_back; i = (i - 1) % 10) { int count = robots_count(train.waiting[i]);
当i == 1时,在2次迭代后,你有5_back为负且有效robots_count(train.waiting[-1);
。
答案 1 :(得分:0)
一旦你修复了bestss指出的逻辑问题,你仍然会遇到mdelay()
忙碌等待的问题,它不会释放CPU。您应该考虑schedule_timeout()
或msleep
。请查看Linux Device Drivers了解更多详情。