Sleep/Wakeup and Linux kernel threads

As a part of understanding the scheduling of kernel thread in linux, I wrote following module code.

#include <linux/module.h>
#include <linux/kernel.h>

#define DBG_FN_ENTRY()  \
do { \
printk(KERN_INFO “Inside function [ %s ]\n”, \
__FUNCTION__); \
} while(0)

struct task_struct *sleeping_task = NULL;
int k = 0;
int func(void *s)
{
int i;

for(i=0;i<20;i++) {
printk(“[%d][%s]\n”, i, (char *)s);
if(sleeping_task)
wake_up_process(sleeping_task);
if(i==10) {
sleeping_task = current;
set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
}
}

int init_module(void)
{
DBG_FN_ENTRY();

kernel_thread(func, (void *)”first”, 0);
kernel_thread(func, (void *)”second”, 0);

return 0;
}

void cleanup_module(void)
{
DBG_FN_ENTRY();
}

This module on compilation and insertion (2.6.17-10-generic) using

insmod hello.ko

produces following output (/var/log/messages) :

Inside function [ init_module ]
[0][first]
[1][first]
[2][first]
[3][first]
[4][first]
[5][first]
[6][first]
[7][first]
[8][first]
[9][first]
[10][first]
[0][second]
[1][second]
[2][second]
[3][second]
[4][second]
[5][second]
[6][second]
[7][second]
[8][second]
[9][second]
[10][second]
[11][first]
[12][first]
[13][first]
[14][first]
[15][first]
[16][first]
[17][first]
[18][first]
[19][first]
[11][second]
[12][second]
[13][second]
[14][second]
[15][second]
[16][second]
[17][second]
[18][second]
[19][second]

Mistakes that I made and rectified to make it work (..arrgh confessions are painful !)

> used schedule()  without changing the task state, task state remained TASK_RUNNING and hence the thread got scheduled again.

> did not wak up the process and hence threads did not get rescheduled, leading to output only upto the counter 10 for both the threads.

I got hold of an article (slightly late..) on LWN about sleeping/wakeup. worth going.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s