Linux work queues are meant to be kernel level threads with process context. I was trying to use it as an alternative to kthread which has no specific process context. But how do I pass data to work queue? work_struct has a data field which is of type atomic_long_t. I could not pass pointer to this field. How do I do it?
Also I could not find a single concrete example of work queue. Can you suggest one?
If you want to pass data to your work queue function, just embed the
work_struct
structure inside your own data structure and usecontainer_of
inside your work function to retrieve it.As for a simple example, the kernel is full of it - just
git grep work_struct
. You can look atdrivers/cpufreq/cpufreq.c
(handle_update
function) for a simple example. The article below also embeds an example at the end, but it does not usecontainer_of
and instead relies on the fact that the first member of a structure has the same address as its parent:http://www.ibm.com/developerworks/linux/library/l-tasklets/index.html
It seems like solved, and you have been very helpful to me in order to understand how to use the Work Queues. I give you some code of a simple example in my github, hoping it will be helpful to anyone:
https://github.com/m0r3n/kernel_modules/blob/master/workQueue.c
You can compile with the following Makefile:
Insert the module by:
And see the logs:
EDIT: I just added the delayed version:
https://github.com/m0r3n/kernel_modules/blob/master/workQueueDelayed.c
By default the work function is called with work struck as parameter. Inside the thread the data element of the structure can easily be obtained. Also a Gnurou, to get access of more data, the work struct can be put inside a implementation specific structure and using the container of macro inside the thread all the data can be accessed.
A simple description about workqueue
worqueue are interrupt handling bottom half mechanishm, where a part of work is given to a kernel thread to execute later with preemtion on an interrupts enable. A percpu thread events/n is created by kernel , threads can also be created by drivers code.A structure is used to identify the thread, an important parameter inside the structure is the name field.It also contains a per cpu structure which in turn contains the waitqueue head on which the thread waits and a link list to add the structure that defines the work i.e. the function and the data .The worker thread gets that structure as the input parameter.The thread runs and wait on the waitqueue for someone to wakeup the thread. A work structure is created defining the function . When an workqueue is schedule, the structure is added to the tail of the link list and the worker thread is woken up. On waking up, the worker thread runs through the link list defined in the per cpu structure and start executing the functions defined with the work structure as parameter. After executing it removes the entry from the link list.