天天看点

linux 内核线程demo

#include<linux/module.h>
#include<linux/sched.h>
#include<linux/pid.h>

#define SWITCH_DELAY_S    (2000)

struct switch_struct {
   int en;
   struct mutex en_lock;   
   struct mutex sw_lock;   
   struct task_struct *task;
}switch_info;

static int scene_switch_task_func(void *data)
{
   int ret = 0;

   while (!kthread_should_stop()) {
	mutex_lock(&(switch_info.sw_lock));	
        //do somethings.
	mutex_unlock(&(switch_info.sw_lock));
	msleep(SWITCH_DELAY_S);
   }

   return 0;
}

static inline void scene_switch_wakeup()  {

}

static inline void scene_switch_sleep()  {

}

static inline void scene_switch_enable()  {
   mutex_lock(&(switch_info.en_lock));
   if(!switch_info.en)  {   	
	  get_task_struct(switch_info.task); 
	  wake_up_process(switch_info.task); 	 
	  switch_info.en = 1;
   } 
   mutex_unlock(&(switch_info.en_lock)); 
}

static inline void scene_switch_disenable()  {
	mutex_lock(&(switch_info.en_lock));  
	if(switch_info.en)	{	
	   kthread_stop(switch_info.task);
	   put_task_struct(switch_info.task);	
	   switch_info.en = 0;
	}
	mutex_unlock(&(switch_info.en_lock));
}


static void vfe_scene_kthread(struct vfe_dev *dev)  {
	switch_info.en = 0;
	mutex_init(&(switch_info.en_lock));
	mutex_init(&(switch_info.sw_lock));
        switch_info.task = kthread_create(scene_switch_task_func,dev, "scene_switch_task");
	if (IS_ERR(switch_info.task))  {
		printk("Kthread create error.");
	}
}
           

继续阅读