How to create some threads running tha same function
    Parmenides 
    mobile.parmenides at gmail.com
       
    Thu Sep 15 10:20:03 EDT 2011
    
    
  
Hi,
   I will try to test how to create kernel threads and have write a
kernel module which creates a number of kernel threads running the
same function. But the results is somewhat confusing.
	#include <linux/kernel.h>
	#include <linux/kthread.h>
	#include <linux/delay.h>
	#define MAX_KTHREAD  2
	struct task_struct *ktask[MAX_KTHREAD];
	static int my_kthread(void *data)
	{
	     int nr = *(int *)data;
	     while (!kthread_should_stop()){
		  ssleep(1);
		  printk(KERN_ALERT "This is mythread[%d].\n", nr);
	     }
	     return 0;
	}
	static int kthread_init(void)
	{
	     int i;
	     for (i = 0; i < MAX_KTHREAD; i++){
		  ktask[i] = kthread_run(my_kthread, &i, "mythread[%d]", i);
	     }
	     return 0;
	}
	static void kthread_exit(void)
	{
	     int i;
	     for (i = 0; i < MAX_KTHREAD; i++){
		  if (ktask[i]){
		       kthread_stop(ktask[i]);
		       ktask[i] = NULL;
		  }
	     }
	}
	module_init(kthread_init);
	module_exit(kthread_exit);
	MODULE_LICENSE("GPL");
	MODULE_AUTHOR("Shakespeare");
	MODULE_DESCRIPTION("This is a test program of kthread.");
The messages on the screen are:
	This is mythread[-929820448].
	This is mythread[1].
	This is mythread[-929820448].
	This is mythread[1].
	This is mythread[-929820448].
	...	...	...
I wonder why the first thread's number is not zero rather than -929820448.
Furthermore, when running again with MAX_KTHREAD == 3, the messages are:
	This is mythread[1].
	This is mythread[2].
	This is mythread[1].
	This is mythread[1].
	This is mythread[2].
	This is mythread[1].
	This is mythread[1].
	This is mythread[2].
	...	...	...
There should be 3 threads running, but only two of them appear. The
first thread get lost.
    
    
More information about the Kernelnewbies
mailing list