Nat*_*sha 5 multithreading linux-kernel
我需要将kthread函数用于工作处理器,两者之间的区别对我来说不是很清楚.这是我对这些领域的理解.
struct kthread_worker {
spinlock_t lock; // lock to update the work queue
struct list_head work_list; // list kthread_work items
struct task_struct *task; // handle for thread
struct kthread_work *current_work; // ?
};
struct kthread_work {
struct list_head node; // list of threads?
kthread_work_func_t func; // func to execute?
struct kthread_worker *worker; // worker associated with this work item
};
Run Code Online (Sandbox Code Playgroud)
我的问题是:
对不明确的领域的任何澄清.
kthread_work_func_t是一个func ptr,期待kthread_work的参数.这是如何运作的?它应该指向您希望线程执行的功能,对吧?
kthread_worker是一个可以执行works()的worker.工作可以随时添加到工作人员.工人一个接一个地执行工作.如果当前没有可用的工作,则工作人员等待.kthread_work
kthread_work_func_t是一个func ptr,期待kthread_work的参数.这是如何运作的?它应该指向您希望线程执行的功能,对吧?
是的,它只是你想要作为工作执行的功能.
如果只有一个工作使用这个函数(例如,这是某种垃圾收集器),函数可能只是忽略它的参数.
如果您想要使用相同功能但参数不同的多个作品,可以将 kthread_work结构嵌入到包含以下参数的结构中:
struct my_work
{
struct kthread_work work; //Base work object
int i; // Your parameter
}
// Parametrized work function
void my_func(struct kthread_work* work)
{
// Extract actual work object
struct my_work* my_work = container_of(work, struct my_work, work);
// Parameter for the work
int i = my_work->i;
// Do something
...
// Free memory used for work object
kfree(my_work);
}
// Helper for add your work with given parameter
void add_my_work(struct kthread_worker* worker, int i)
{
// Allocate your work object on the heap
struct my_work* my_work = kmalloc(sizeof(struct my_work), GFP_KERNEL);
// Initialize base work structure
init_kthread_work(&my_work->work, &my_func);
// Store parameter
work->i = i;
queue_kthread_work(worker, &my_work->work);
}
Run Code Online (Sandbox Code Playgroud)
对不明确的领域的任何澄清.
正如您在前面的示例中所看到的,知道字段struct kthread_worker并且struct kthread_work很少用于使用它.但实际上语义很简单:
struct kthread_worker {
spinlock_t lock; // lock to update the work queue
struct list_head work_list; // list kthread_work items
struct task_struct *task; // handle for thread
struct kthread_work *current_work; // (+) currently executed work object
};
struct kthread_work {
struct list_head node; // (+) element in the kthread_worker.work_list
kthread_work_func_t func; // func to execute
struct kthread_worker *worker; // worker associated with this work item
};
Run Code Online (Sandbox Code Playgroud)