#include
#include
#include
#include
#include
struct my_work{
int idx;
struct work_struct work;
};
struct workqueue_struct *workqueue = NULL;
struct my_work work1={
.idx = 1,
};
struct task_struct *test_task1;
int thread_func(void *data);
void work_func(struct work_struct *work)
{
struct my_work *my_work;
if(work != NULL)
{
//my_work = container_of(work, struct my_work, work);
//printk("work form work%d\n",my_work->idx);
}
printk("working\n");
}
int thread_func(void *data)
{
data = data;
while(!kthread_should_stop())
{
set_current_state(TASK_UNINTERRUPTIBLE); //没有这句话为什么会一直打印,为什么不休眠??
printk("task add work!\n");
/*添加work到工作队列*/
queue_work(workqueue, &work1.work); //如果在上次的任务还没处理完,多次重复添加相同的work,只会执行一次
schedule_timeout(HZ);
if (signal_pending(current))
{
flush_signals(current);
}
}
return 0;
}
int create_thread(struct task_struct *task, void *arg)
{
int err;
task = kthread_create(thread_func, arg, "test_task");
if(IS_ERR(task))
{
printk("Unable to start kernel thread.\n");
err = PTR_ERR(task);
task = NULL;
return err;
}
/*唤醒任务*/
wake_up_process(task);
return 0;
}
static int __init mymodule_init(void)
{
int err;
workqueue = create_singlethread_workqueue("single_thread_workqueue");
if (NULL == workqueue)
{
return -ENOMEM;
}
INIT_WORK(&work1.work,work_func);
err = create_thread(test_task1,"task1");
if(err != 0 )
{
return err;
}
printk("My module worked!\n");
return 0;
}
static void __exit mymodule_exit(void)
{
printk("Unloadling my module.\n");
if(test_task1)
{
kthread_stop(test_task1);
test_task1 = NULL;
}
if (workqueue)
{
flush_workqueue(workqueue); //确保所有的工作都已经完成才释放资源
destroy_workqueue(workqueue);
}
printk("Unloaded my module.\n");
return;
}
module_init(mymodule_init);
module_exit(mymodule_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("test@163.com");
MODULE_DESCRIPTION("JUST FOR TEST!");[/code]
ludehp 于 2015-10-14 15:13:14发表:
解决了,犯了个低级错误
int create_thread(struct task_struct *task, void *arg)
函数应该是
int create_thread(struct task_struct **task, void *arg)
但是有一点还是不明白,如果去掉set_current_state(TASK_UNINTERRUPTIBLE)这一句,好像线程没法休眠,为什么会这样呢?