本文共 2205 字,大约阅读时间需要 7 分钟。
代码:
#include#include #include #include #include #include #include static struct task_struct * task1;static struct task_struct * task2;static int number = 0;int i, j;int num = 0;DEFINE_SPINLOCK(mylock);static wait_queue_head_t wait_queue;static int thread_fun1(void* data){ init_waitqueue_head(&wait_queue);// printk(KERN_INFO"thread1: number = %d \n", number); for(i = 0; i < 10; i++) { spin_lock(&mylock); number++; spin_unlock(&mylock); printk("thread1: number= %d \n", number); msleep(1000); } j = 1; while(!kthread_should_stop()) { wait_event_interruptible_timeout(wait_queue, false, HZ); printk("thread 1 sleep .. %d \n", j++); } return 0;}static int thread_fun2(void *data){ //printk(KERN_INFO"thread2: number = %d\n",number); init_waitqueue_head(&wait_queue); for(i=0;i<10;i++){ spin_lock(&mylock); //加锁以保证同步 number++; spin_unlock(&mylock); printk("thread2: number = %d\n",number); msleep(1000); } j=1; while(!kthread_should_stop()){ wait_event_interruptible_timeout(wait_queue,false,HZ); printk("thread 2 sleeping..%d\n", j++); } return 0;}static int __init hello_init(void){ task1 = kthread_run(thread_fun1,NULL,"mythread1"); // run a kthread return 进程描述符 if(IS_ERR(task1)){ printk("thread1 create failed!\n"); }else{ printk("thread1 create success!\n"); } task2 = kthread_run(thread_fun2,NULL,"mythread2"); if(IS_ERR(task2)){ printk("thread2 create failed!\n"); }else{ printk("thread2 create success\n"); } return 0;}static void __exit hello_exit(void){ if(!IS_ERR(task1)){ //这里判断指针是否正常 kthread_stop(task1); printk("thread1 finished!\n"); } if(!IS_ERR(task2)){ kthread_stop(task2); printk("thread2 finished!\n"); }}module_init(hello_init);module_exit(hello_exit);MODULE_LICENSE("GPL");
分析结果:
一个非常简单的内核级多线程程序学习!
转载地址:http://puzjn.baihongyu.com/