博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
linux下内核多线程的简单实现
阅读量:3705 次
发布时间:2019-05-21

本文共 2205 字,大约阅读时间需要 7 分钟。

内核态多线程的 学习


  • 方法、结构介绍
  1. task_struct // 用户定义 j 进程描述符,linux中把并不对进程和线程做强制区分。
  2. kthread_run() //用户创建一个线程并运行函数原型如下 kthread_run(threadfn, data, namefmt, …), threadfn 是线程被唤醒后执行的方法。
  3. kthead_stop() //用于结束一个线程的运行,需要注意的是调用此方法时,该线程必须不能已经结束,否则后果严重。
  4. kthread_should_stop() //用户返回结束标志
  5. wait_event_interruptible_on_timeout() //中断一个线程,知道满足条件或者超时为止

代码:

#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");

在这里插入图片描述

分析结果:

  • i 是全局变量,线程1执行时赋值 为 0,在线程2执行时又赋值为0 所以number打印到 11。

ps -ef 查看线程:
在这里插入图片描述
rmmod 卸载模块:
在这里插入图片描述

一个非常简单的内核级多线程程序学习!

转载地址:http://puzjn.baihongyu.com/

你可能感兴趣的文章
Mybatis01(结果集封装)
查看>>
Tomcat运行时报 cannot be cast to javax.servlet.Servlet
查看>>
使用maven开发项目编译时会漏掉src/main/java下的xml配置文件,导致报错
查看>>
富文本编辑器
查看>>
算法中的双指针思想及常见应用
查看>>
图解排序算法之归并排序
查看>>
图解排序算法之堆排序
查看>>
二分查找
查看>>
BFS问题及相关应用
查看>>
LeetCode中经典的排序问题
查看>>
拓扑排序
查看>>
LeetCode中典型的DFS问题
查看>>
MySQL事务和隔离级别
查看>>
LeetCode中有关哈希表问题
查看>>
计算机网络学习笔记
查看>>
完美代价(贪心算法)
查看>>
矩阵乘法
查看>>
时间转化·
查看>>
二进制数数
查看>>
蓝桥杯大小写转换
查看>>