内核态多线程的 学习
- 方法、结构介绍
- task_struct // 用户定义 j 进程描述符,linux中把并不对进程和线程做强制区分。
- kthread_run() //用户创建一个线程并运行函数原型如下 kthread_run(threadfn, data, namefmt, …), threadfn 是线程被唤醒后执行的方法。
- kthead_stop() //用于结束一个线程的运行,需要注意的是调用此方法时,该线程必须不能已经结束,否则后果严重。
- kthread_should_stop() //用户返回结束标志
- wait_event_interruptible_on_timeout() //中断一个线程,知道满足条件或者超时为止
代码:
#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>
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");
分析结果:
- i 是全局变量,线程1执行时赋值 为 0,在线程2执行时又赋值为0 所以number打印到 11。
ps -ef 查看线程:
rmmod 卸载模块:
一个非常简单的内核级多线程程序学习!