Multithreading kthread使用100%cpu内核检查kthread_should_stop()

Multithreading kthread使用100%cpu内核检查kthread_should_stop(),multithreading,linux-kernel,queue,linux-device-driver,Multithreading,Linux Kernel,Queue,Linux Device Driver,我有一个由中断驱动的进程填充并由kthread清空的项目队列 问题是清空队列的kthread占用了我的一个内核的100%cpu。似乎当队列为空时,while循环会不断检查kthread\u是否应该反复停止,并且只有在我停止线程时才会释放内核 #DEFINE MY_BUF_SIZE 100 struct item_struct { unsigned char buff[MY_BUF_SIZE]; struct list_head list; }; struct item_

我有一个由中断驱动的进程填充并由kthread清空的项目队列

问题是清空队列的kthread占用了我的一个内核的100%cpu。似乎当队列为空时,while循环会不断检查kthread\u是否应该反复停止,并且只有在我停止线程时才会释放内核

#DEFINE MY_BUF_SIZE 100

struct item_struct {
    unsigned char buff[MY_BUF_SIZE];
    struct list_head list;
};  

struct  item_struct itemList;
struct task_struct *forward_items_thread;

void forward_items(void * args) {
    while (!kthread_should_stop()){
        struct item_struct *item, *tmpItem;

        list_for_each_entry_safe(item, tmpItem, &itemList.list, list)
        {
            my_send_items(item);
            list_del(&item->list);
            kfree(item);
        }
    }
}

void setup_item_forwarding(void){
    int err;

    INIT_LIST_HEAD(&itemList.list); 
    forward_items_thread = kthread_create(forward_items);
    if (IS_ERR(forward_items_thread)) {
        printk("kthread create failed");
        err = PTR_ERR(forward_items_thread);
        goto err_return;
    }

    err = wake_up_process(forward_items_thread);
    if (err == 1) {
        printk("forward_items_thread has woken.\n");
    }
    else {
        printk("forward_items_thread failed to wake.\n");
    }

err_return:
//do cleanup
}
我不想使用睡眠/延迟,因为使用睡眠/延迟的进程对~1ms的时间非常敏感

如何使kthread处理排队的项目而不占用CPU上的太多时间?

在使线程可中断后,可以使用schedule

void forward_items(void * args) {
    while (!kthread_should_stop()){
        struct item_struct *item, *tmpItem;

        // set interruptible
        set_current_state(TASK_INTERRUPTIBLE);

        // do I have anything to do ?
        if(my_func_no_task_to_do())
        {
             schedule();
        }

        list_for_each_entry_safe(item, tmpItem, &itemList.list, list)
        {
            my_send_items(item);
            list_del(&item->list);
            kfree(item);
        }
     }
}

只要让kthread在列表为空时等待即可。使用一个wait_*宏。关于kthread\u应该\u停止有一些具体的问题:1。您需要检查此条件以及列表是否为空。2.等待应该是可中断的,因此停止线程将中断等待。