c - Linux 内核线程

标签 c linux multithreading kernel

所以我正在开发一个 linux 内核模块,它需要在由 kthread 启动的单独线程中进行无限等待循环。下面是kthread运行的函数,train.queue_mutex是kthread之前初始化的mutex(via 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;
}

最佳答案

 for (i = train.stop ;i != five_back; i = (i - 1) % 10)
 {
    int count = robots_count(train.waiting[i]);

当 i == 1 时,你有 five_back 负数并且有效地 robots_count(train.waiting[-1); 经过 2 次迭代。

关于c - Linux 内核线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5305573/

相关文章:

c - 三元运算符。条件自动类型转换

linux - 当进程运行在 X 服务器上时会发生什么变化

multithreading - Kotlin 协程的使用

ios - 分派(dispatch)到并发队列导致在主线程上执行?

c - c中的多线程问题

c - gcc 中已经定义了哪些 C 预处理器宏?

c - 使用 glib 的 g_new() 进行内存分配

c - 这个类型结构定义的指针是什么意思(在 C 中)?

linux - 安装 posix 时出现 npm install 错误

linux - 当从 ls | 传送结果时 head 不起作用grep