前几天看了看C语言多线程,今天就想看看linux内核多线程是怎么一回事。经过多方资料查询,写了一个小程序和大家分享下。
在这里先介绍程序中用到的几个方法、结构。
1.task_struct //用户定义j进程描述符,linux中把并不对进程和线程做强制区分
2.kthread_run() //用户创建一个线程并运行函数原型如下kthread_run(threadfn, data, namefmt, ...),threadfn是线程被唤醒后执行的方法,
3.kthread_stop() //用于结束一个线程的运行,需要注意的是调用此方法时,该线程必须不能已经结束,否则后果严重
4.kthread_should_stop() //用户返回结束标志
5.wait_event_interruptible_on_timeout() //中断一个线程,知道满足条件或者超时为止
下面贴出代码:
kthread_test.c
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/delay.h>
#include<linux/wait.h>
#include<linux/kthread.h>
#include<linux/spinlock.h>
MODULE_LICENSE("GPL");
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 sleeping..%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");
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)
执行后结果:
ps -ef 查看线程:
rmmod 卸载模块:
小程序就是这样,不知本人是否讲的清楚或者有什么错误,若是有的话还请各位提出来,咱们共同学习进步!