【转】工作队列(workqueue)

Linux内核工作队列workqueue详解 linux 内核 workqueue详解 阅读详情

原博 http://blog.chinaunix.net/uid-24148050-id-296982.html



一、workqueue简介

workqueue与tasklet类似,都是允许内核代码请求某个函数在将来的时间被调用(抄《ldd3》上的)
每个 workqueue就 是一个内核进程。

workqueue与tasklet的区别:
   1.tasklet是通过软中断实现的,在软中断上下文中运行,tasklet代码必须是原子的
     workqueue是通过内核进程实现的,就没有上述限制的,最爽的是,工作队列函数可以休眠 
         
     PS: 我的驱动模块就是印在计时器中调用了可休眠函数,所以出现了cheduling while atomic告警
         内核计时器也是通过软中断实现的

   2.tasklet始终运行在被初始提交的同一处理器上,workqueue不一定
   3.tasklet不能确定延时时间(即使很短),workqueue可以设定延迟时间


二、workqueue的API

 
workqueue的API自2.6.20后发生了变化

  1. #include <linux/workqueue.h>
  2. struct workqueue_struct;
  3. struct work_struct;

  4. struct workqueue_struct *create_workqueue(const char *name);
  5. void destroy_workqueue(struct workqueue_struct *queue);

  6. INIT_WORK(_work, _func);
  7. INIT_DELAYED_WORK(_work, _func);

  8. int queue_work(struct workqueue_struct *wq, struct work_struct *work);
  9. int queue_delayed_work(struct workqueue_struct *wq,struct delayed_work *dwork, unsigned long delay);

  10. int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
  11.             struct delayed_work *dwork, unsigned long delay);

  12. int cancel_work_sync(struct work_struct *work);
  13. int cancel_delayed_work_sync(struct delayed_work *dwork);

  14. void flush_workqueue(struct workqueue_struct *wq);
Workqueue编程接口

序号

接口函数

说明

1

create_workqueue

用于创建一个workqueue队列,为系统中的每个CPU都创建一个内核线程。输入参数:

@name:workqueue的名称

2

create_singlethread_workqueue

用于创建workqueue,只创建一个内核线程。输入参数:

@name:workqueue名称

3

destroy_workqueue

释放workqueue队列。输入参数:

@ workqueue_struct:需要释放的workqueue队列指针

4

schedule_work

调度执行一个具体的任务,执行的任务将会被挂入Linux系统提供的workqueue——keventd_wq输入参数:

@ work_struct:具体任务对象指针

5

schedule_delayed_work

延迟一定时间去执行一个具体的任务,功能与schedule_work类似,多了一个延迟时间,输入参数:

@work_struct:具体任务对象指针

@delay:延迟时间

6

queue_work

调度执行一个指定workqueue中的任务。输入参数:

@ workqueue_struct:指定的workqueue指针

@work_struct:具体任务对象指针

7

queue_delayed_work

延迟调度执行一个指定workqueue中的任务,功能与queue_work类似,输入参数多了一个delay。



下面实例是不指定delay时间的workqueue
(代码基于2.6.24)

  1. struct my_work_stuct{
  2.     int test;
  3.     struct work_stuct save;
  4. };

  5. struct my_work_stuct test_work; 
  6. struct workqueue_struct *test_workqueue;

  7. void do_save(struct work_struct *p_work)
  8. {
  9.     struct my_work_struct *p_test_work = container_of(p_work, struct my_work_stuct, save);
  10.     printk("%d\n",p_test_work->test);
  11. }
  12.   
  13. void test_init()
  14. {
  15.     test_workqueue = create_workqueue("test_workqueue");
  16.     if (!test_workqueue)
  17.         panic("Failed to create test_workqueue\n");

  18.     INIT_WORK(&(test_work.save), do_save);

  19.     queue_work(test_workqueue, &(test_work.save));
  20. }

  21. void test_destory(void)
  22. {
  23.     if(test_workqueue)
  24.         destroy_workqueue(test_workqueue);
  25. }


三、workqueue的实现


工作队列workqueue不是通过软中断实现的,它是通过内核进程实现的



首先,创建一个workqueue,实际上就是建立一个内核进程

  1. create_workqueue("tap_workqueue")
  2. --> __create_workqueue(“tap_workqueue”, 0, 0)
  3. --> __create_workqueue_key((name), (singlethread), (freezeable), NULL, NULL){
  4.          wq = kzalloc(sizeof(*wq), GFP_KERNEL);
  5.          wq->cpu_wq = alloc_percpu(struct cpu_workqueue_struct);
  6.          wq->name = name;
  7.          wq->singlethread = singlethread;
  8.          wq->freezeable = freezeable;
  9.          INIT_LIST_HEAD(&wq->list);

  10.          for_each_possible_cpu(cpu) {
  11.              cwq = init_cpu_workqueue(wq, cpu);
  12.              err = create_workqueue_thread(cwq, cpu);
  13.              start_workqueue_thread(cwq, cpu);
  14.          }
  15.     }

create_workqueue_thread 建立了一个内核进程 worker_thread(linux_2_6_24/kernel/workqueue.c)
  1. create_workqueue_thread(struct cpu_workqueue_struct *cwq, int cpu)
  2. {
  3.     struct workqueue_struct *wq = cwq->wq;

  4.     const char *fmt = is_single_threaded(wq) ? "%s" : "%s/%d";
  5.     struct task_struct *p;

  6.     p = kthread_create(worker_thread, cwq, fmt, wq->name, cpu);

  7.     if (IS_ERR(p))
  8.         return PTR_ERR(p);

  9.     cwq->thread = p;

  10.     return 0;
  11. }

内核进程worker_thread做的事情很简单,死循环而已,不停的执行workqueue上的work_list
(linux_2_6_24/kernel/workqueue.c)

  1. int worker_thread (void *__cwq)
  2. {
  3.     struct cpu_workqueue_struct *cwq = __cwq;
  4.     /*下面定义等待队列项*/
  5.     DEFINE_WAIT(wait);

  6.     /*下面freezeable一般为0*/
  7.     if (cwq->wq->freezeable)
  8.         set_freezable();

  9.     /*提高优先级别*/
  10.     set_user_nice(current, -5);

  11.     for (;;) {
  12.         /*在cwq->more_work上等待, 若有人调用queue_work,该函数将调用wake_up(&cwq->more_work) 激活本进程*/
  13.         prepare_to_wait(&cwq->more_work, &wait, TASK_INTERRUPTIBLE);

  14.         /*work队列空则切换出去*/
  15.         if (!freezing(current) && !kthread_should_stop() && list_empty(&cwq->worklist))
  16.             schedule();


  17.         /*切换回来则结束等待 说明有人唤醒cwq->more_work上的等待 有work需要处理*/
  18.         finish_wait(&cwq->more_work, &wait);

  19.         /*下面空,因为没有定义电源管理*/
  20.         try_to_freeze();

  21.         if (kthread_should_stop())
  22.             break;

  23.         /*run_workqueue依次处理工作队列上所有的work*/
  24.         run_workqueue(cwq);
  25.     }
  26.     return 0;
  27. }


  28. /*run_workqueue依次处理工作队列上所有的work*/
  29. static void run_workqueue(struct cpu_workqueue_struct *cwq)
  30. {
  31.     spin_lock_irq(&cwq->lock);
  32.     cwq->run_depth++;
  33.     if (cwq->run_depth > 3) {
  34.         /* morton gets to eat his hat */
  35.         printk("%s: recursion depth exceeded: %d\n",
  36.             __FUNCTION__, cwq->run_depth);
  37.         dump_stack();
  38.     }

  39.     while (!list_empty(&cwq->worklist)) {
  40.         struct work_struct *work = list_entry(cwq->worklist.next,
  41.                         struct work_struct, entry);
  42.         work_func_t f = work->func;
  43. #ifdef CONFIG_LOCKDEP
  44.         /*
  45.          * It is permissible to free the struct work_struct
  46.          * from inside the function that is called from it,
  47.          * this we need to take into account for lockdep too.
  48.          * To avoid bogus "held lock freed" warnings as well
  49.          * as problems when looking into work->lockdep_map,
  50.          * make a copy and use that here.
  51.          */
  52.         struct lockdep_map lockdep_map = work->lockdep_map;
  53. #endif

  54.         cwq->current_work = work;
  55.         list_del_init(cwq->worklist.next);
  56.         spin_unlock_irq(&cwq->lock);

  57.         BUG_ON(get_wq_data(work) != cwq);
  58.         work_clear_pending(work);
  59.         lock_acquire(&cwq->wq->lockdep_map, 0, 0, 0, 2, _THIS_IP_);
  60.         lock_acquire(&lockdep_map, 0, 0, 0, 2, _THIS_IP_);

  61.         f(work); /*执行work项中的func*/
  62.        
  63.         lock_release(&lockdep_map, 1, _THIS_IP_);
  64.         lock_release(&cwq->wq->lockdep_map, 1, _THIS_IP_);

  65.         if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
  66.             printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
  67.                     "%s/0x%08x/%d\n",
  68.                     current->comm, preempt_count(),
  69.                         task_pid_nr(current));
  70.             printk(KERN_ERR " last function: ");
  71.             print_symbol("%s\n", (unsigned long)f);
  72.             debug_show_held_locks(current);
  73.             dump_stack();
  74.         }

  75.         spin_lock_irq(&cwq->lock);
  76.         cwq->current_work = NULL;
  77.     }
  78.     cwq->run_depth--;
  79.     spin_unlock_irq(&cwq->lock);
  80. }


将一个work加入到指定workqueue的work_list中(文件linux_2_6_24 /kernel /workqueue .c)

   int fastcall queue_work (struct workqueue_struct  *wq , struct work_struct  *work )
  1. {
  2.     int ret = 0;

  3.     if (!test_and_set_bit(WORK_STRUCT_PENDING, work_data_bits(work))) {
  4.         BUG_ON(!list_empty(&work->entry));
  5.         __queue_work(wq_per_cpu(wq, get_cpu()), work);
  6.         put_cpu();
  7.         ret = 1;
  8.     }
  9.     return ret;
  10. } 


  11. /* Preempt must be disabled. */
  12. static void __queue_work(struct cpu_workqueue_struct *cwq, struct work_struct *work)
  13. {
  14.     unsigned long flags;

  15.     spin_lock_irqsave(&cwq->lock, flags);
  16.     insert_work(cwq, work, 1);
  17.     spin_unlock_irqrestore(&cwq->lock, flags);
  18. }

  19. static void insert_work(struct cpu_workqueue_struct *cwq,
  20.                 struct work_struct *work, int tail)
  21. {
  22.     set_wq_data(work, cwq);
  23.     /*
  24.      * Ensure that we get the right work->data if we see the
  25.      * result of list_add() below, see try_to_grab_pending().
  26.      */
  27.     smp_wmb();
  28.     if (tail)
  29.         list_add_tail(&work->entry, &cwq->worklist);
  30.     else
  31.         list_add(&work->entry, &cwq->worklist);
  32.     wake_up(&cwq->more_work);
  33. }



四、共享队列

其实内核有自己的一个workqueue,叫keventd_wq,这个工作队列也叫做“共享队列”。
do_basic_setup --> init_workqueues --> create_workqueue("events"); 

若驱动模块使用的workqueue功能很简单的话,可以使用“共享队列”,不用自己再建一个队列
使用共享队列,有这样一套API

  1. int schedule_work(struct work_struct *work)
  2. {
  3.     queue_work(keventd_wq, work);
  4. }

  5. int schedule_delayed_work(struct delayed_work *dwork,unsigned long delay)
  6. {
  7.     timer_stats_timer_set_start_info(&dwork->timer);
  8.     return queue_delayed_work(keventd_wq, dwork, delay);
  9. }

  10. void flush_scheduled_work(void)
  11. {
  12.     flush_workqueue(keventd_wq);
  13. }



内网(极空间)搭建gitlab跳板机转发端口及域名配置 然后,回头尝试用内网地址+15022 clone,成功,用公网的ip+15222 clone失败,那就是定位到时nginx转发的问题了。首先想到的就是 git clone是通过ssh的22端口进行下载的,那就需要打通22端口,则又配置22端口的nginx转发。然后,我通过ssh命令,做一个端口转发,以实现内网穿透,将服务端口链接到跳板机上。然后穿透到阿里云服务器跳板机的端口,只能内网访问,需要用nginx做个转发,才能用公网ip进行访问。然后,如上,我的80端口,映射15080,22端口映射15022。 阅读详情

相关推荐

01-SA8155 QNX 虚拟机Hypervisor

Hypervisor运行在Host OS操作系统上,其他操作系统均在Hypervisor上运行。:Hypervisor直接运行在硬件上,操作系统在Hypervisor之上运行。终止(关闭):echo control 0 dev/vmm。路径:qnx_ap/AMSS/platform/vm/resources/关闭/终止 qvm(GVM):slay -s SIGQUIT qvm。", //host PVM --- 主机。不直接操作/dev/vmm 实现关闭,启动vm。

静虚待令,有物混成 1万+

BUG: scheduling while atomic检测机制原理与问题处理

当在任务切换过程中,如果调度器检测到切换前的环境属于原子操作,是禁止发生任务切换的,便会输出“BUG: scheduling while atomic:”等异常打印,之后会根据配置决定是否触发panic,重启系统。Linux内核调度器中,每次任务调度发生时,都会检查当前是否处于原子操作环境中,如果是,则打印出“BUG: scheduling while atomic:***”异常信息,打印出调度栈。如果此时,内核中配置了“panic_on_warn”,则会触发kernel panic,造成系统重启。

kkqier的博客 5402

CentOS7上装不了最新Chrome?别折腾依赖了,试试这个老版本安装法(附103.0.5060.24 beta下载地址)

本文提供了在CentOS7上安装兼容版Chrome的详细指南,解决了因GLIBC版本限制导致的最新版Chrome无法安装的问题。推荐使用Chrome 103.0.5060.24 beta版本,并附有下载地址和完整安装步骤,包括禁用自动更新和配套工具安装,确保系统稳定性和功能完整性。

weixin_29289821的博客 579

工作队列(workqueue)

项目需要,在驱动模块里用内核计时器timer_list实现了一个状态机。 郁闷的是,运行时总报错“Scheduling while atomic”,网上搜了一下: "Scheduling while atomic" indicates that you've tried to sleep somewhere that you shouldn't - like within a spin

xp_super的专栏 811

Win11只读模式无法关闭的终极解决方案

通过以上方法,我们应该能够解决Windows 11中文件夹无法取消只读状态的问题。如果问题仍然存在,请确保你的账户具有足够的权限来修改文件夹属性,并考虑是否有其他安全软件或策略阻止了权限更改。在操作过程中,请务必小心谨慎,避免误操作导致数据丢失或系统损坏。希望本文能够帮助到大家!

mmoo_python的博客 1万+

IDEA 导入 jbolt项目(实验室非公开项目)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录准备一、准备数据库二、IDEA导入jbolt项目 准备 在实验室群文件中下载jbolt.zip和mysql.sql两个文件 将其解压到自己的目录下 一、准备数据库 打开Navicat新建一个jbolt数据库(字符集为utf8) 导入mysql.sql文件 数据库导入完毕 二、IDEA导入jbolt项目 点击打开一个项目 选择jbolt文件夹 以Maven形式打开 打开pom.xml 在里面添加jetty-server依赖

weixin_44094842的博客 983

BUG: scheduling while atomic 分析Linux内核

在编写Linux内核模块时遇到BUG: scheduling while atomic 本文对其进行分析

咸鱼弟的博客 3475

AI 赋能 DBA:如何用 DeepSeek 等大模型简化数据库管理工作

数据库管理员(DBA)的工作涉及 SQL 优化、故障排查、性能监控等复杂任务。而 DeepSeek、ChatGPT 等大模型可以大幅减少重复劳动,提高 DBA 的工作效率。:某电商平台的订单查询 SQL 执行缓慢(平均 5s),DBA 需要优化。:DBA 需要监控 MySQL 的慢查询,但不想手动写脚本。:某金融系统频繁出现数据库死锁,DBA 需要快速定位原因。:大模型可分析 SQL 执行计划,推荐索引优化方案。:用日常语言查询数据库,无需写复杂 SQL。:一键生成监控、备份、数据迁移脚本。

专注于编程、AI、人工智能等多个领域内容研究和分析 575

scheduling while atomic 报错解决

结合起来,简单来说,就是自旋锁启动和释放过程中,应该保证整个过程是原子操作(即不可被中断),笔者的项目在启动自旋锁后,进行了写文件操作,写文件需要启动线程,于是无法保证自旋锁完整的执行,被写文件操作中断。在多线程或并发编程中,当一个线程正在执行原子操作期间,另一个线程通常不能进行调度,即不能在原子操作期间对该线程进行上下文切换。如果在执行原子操作期间进行调度,可能会破坏原子性,导致数据一致性问题或其他异常。

weixin_44043727的博客 1002

人工智能大语言模型微调技术:SFT 监督微调、LoRA 微调方法、P-tuning v2 微调方法、Freeze 监督微调方法

人工智能大语言模型微调技术:SFT 监督微调、LoRA 微调方法、P-tuning v2 微调方法、Freeze 监督微调方法

丨汀、的博客 4万+

pandas教程:2012 Federal Election Commission Database 2012联邦选举委员会数据库

里面包含了支持者的名字,职业和雇主,地址,赞助金额。我们可以已经能想到如何切割、整理数据,来提取赞助者的统计数据,或提取宣传活动的模式,这里我们展示一些不同的分析方法。可以看到有些职业是同一种工作类型,指代的是同一个东西。这两个连续操作是分别独立执行的,一个结束后,另一个才开始。上,这里我是把数据集压缩成了ZIP格式,解压后能正常导入)。我觉得也有必要好好了解一下,这个网站做了很好的讲解,),所以我们最好添加这样的信息。这样的情况,即把两个索引操作连在一起。,发现映射关系被正常执行了,所以这里的。

Cachel Wood的博客 356

BUG: scheduling while atomic: swapper/0/0/0x00010000

BUG: scheduling while atomic: swapper/0/0/0x00010000

我的博客 1431

Windows Server 2019 服务器一天之中内存利用率越来越高直到死机,疑似内存泄漏

环境: 华为桌面云虚拟机 Windows Server 2019 版本1809 OS内部版本17763.107 问题描述: Windows Server 2019服务器 一天之中内存利用率越来越高直到死机,不断扩容内存从10G到16G一重启就正常然后慢慢又循环,连续几天都这样,疑似内存泄漏 内存泄漏是什么? 内存泄漏指由于疏忽或错误造成程序未能释放已经不再使用的内存。内存泄漏并非指内存在物理上的消失,而是应用程序分配某段内存后,由于设计错误,导致在释放该段内存之前就失去了对该段内存的控制,从而造成了内存的浪

本博客,博文仅代表个人操作经验,不能完全解决你的问题,仅供参考,佛系回复。 5404

Linux中断管理 (3)workqueue工作队列【转】

转自:https://www.cnblogs.com/arnoldlu/p/8659988.html 目录: 《Linux中断管理》 《Linux中断管理 (1)Linux中断管理机制》 《Linux中断管理 (2)软中断和tasklet》 《Linux中断管理 (3)workqueue工作队列》 关键词: 工作队列的原理是把work(需要推迟执行的函数)交由一个...

weixin_30919571的博客 414

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

linux查看work队列大小,linux工作队列 - workqueue总览【转】

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本文链接:https://blog.csdn.net/l289123557/article/details/52551176workqueue归入中断子系统是由于和中断处理有密切关系,写博客重要在于整理自己的思绪,写的时候会把一些不懂的细节问题暴露出来,这样会把问题看的更透彻,workqueue...

weixin_31974659的博客 432

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

workqueue 工作队列

Workqueue工作队列是利用内核线程来异步执行工作任务的通用机制;Workqueue工作队列可以用作中断处理的机制,利用进程上下文来执行中断处理中耗时的任务,因此它允许睡眠,而Softirq和Tasklet在处理任务时不能睡眠;在中断处理过程中,或者其他子系统中,调用workqueue的调度或入队接口后,通过建立好的链接关系图逐级找到合适的worker,最终完成工作任务的执行;

生活需要深度 2666

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

内核工作队列workqueue 简述

一 引入工作队列(work queue) 之前聊过Linux中断机制分为上半部中断(硬中断)和下半部,顶半部中断用于完成比较紧急的功能,往往只是简单的读取寄存器中的中断状态,并在清除中断标志后,启动下半部,下半部需要完成中断事件的绝大多数任务。我们经常使用tasklet机制(软中断延迟机制)来实现下半部工作,而tasklet机制是一种传统的底半部处理机制,它的执行时机往往放生在顶半部返回的时候,t...

奶牛养殖场小马 6786

linux workqueue工作队列的理解和使用示例

本文使用的内核源码为linux 4.15.2。对wrkqueue知识的较深入的分析和应用

kerwin的专栏 2765

Linux内核工作队列(workqueue)详解

Linux内核工作队列(workqueue)详解

咸鱼弟的博客 1万+

[Linux API]linux 工作队列workqueue

1,功能描述:Linux中的Workqueue机制就是为了简化内核线程的创建。通过调用workqueue的接口就能创建内核线程。并且可以根据当前系统CPU的个 数创建线程的数量,使得线程处理的事务能够并行化。workqueue是内核中实现简单而有效的机制,他显然简化了内核daemon的创建,方便了用户的 编程。工作队列(workqueue)是另外一种将工作推后执行的形式.工作队列可以把工作推后,交由

Joymine的专栏 2613

工作队列 ( workqueue )

由来 在内核代码中,经常会遇到不能或不合适去马上调用某个处理过程,此时希望将该工作推送给某个内核线程执行,这样做的原因有很多,比如: 中断触发了某个过程的执行条件,而该过程执行时间较长或者会调用导致睡眠的函数,则该过程不应该在中断上下文中立即被调用。 类似于中断,一些紧急性的任务不希望执行比较耗时的非关键过程,则需要把该过程提交到低优先级线程执行。比如一个轮询的通信接收线程,它需要快速完成检测和接收数据,而对数据的解析则应该交由低优先级线程慢慢处理。 有时希望将一些工作集中起来以获取批处理的性能;或则合并

ScilogyHunter的博客 5955

捋一下工作队列workqueue

work queue的使用 struct work_struct work; //先定义一个工作 void func(struct work_struct *work) {} //工作的内容 INIT_WORK(work, func) //初始工作,func绑定到work中 schedule_work(&work); ...

m0_37797953的博客 1479

linux 基础知识点之工作队列workqueue

多年前就了解了workqueue着玩意,但理解上就并不是很很深刻,今天重新梳理一下,本文重点的是哪个些现成的demo代码,都是可以直接拿来用的,这就是写这文章的目的和作用,就是为了备份后续工作用到的时候,可以快速Ctrl+c and Ctrl + v,接下来复制些前辈写好的理解概念,再结合一下个所整理得demo。把工作(包括该工作任务的执行回调函数)添加到一个队列,称为workqueue,即工作队列,然后通过worker-pool中的内核工作线程(worker)去执行这个回调函数。

hezhensheng007的专栏 1498

工作队列workqueue

工作队列 <linux/workqueue.h> 工作队列类似 taskets,允许内核代码请求在将来某个时间调用一个函数,不同在于: (1)tasklet 在软件中断上下文中运行,所以 tasklet 代码必须是原子的。而工作队列函数在一个特殊内核进程上下文运行,有更多的灵活性,且能够休眠。 (2)tasklet 只能在最初被提交的处理器上运行,这只是工作队列默认工作方式。 (3)内核代码可以请求工作队列函数被延后一个给定的时间间隔。 (4)tasklet 执行的很快, 短时期, 并且在原子.

qq_34991787的博客 457

工作队列 workqueue

工作队列是内核用于进行延后工作的一种方式。当然驱动模块中使用之前提到的kernel thread就可以完成延后工作了,但是如果每个驱动模块都创建自己的kernel thread,那么内核线程数量过多,这会影响整体的性能。因此,最好的方法就是把这些需求汇集起来,提供一个统一的机制,也就是workqueue了。 它的结构是workqueue_struct; 和工作队列息息相关的是工作元素work_...

weixin_39821531的博客 553

【linux kernel】linux中断管理—workqueue工作队列

linux中断管理—workqueue工作队列 (注)本文所有代码均出自linux版本:4.1.15 一、workqueue工作队列简介 工作队列是除软中断和tasklet以外最常用的一种下半部机制,其基本原理是:把work(需要推迟执行的函数)交由一个内核线程来执行,他总是在进程上下文执行。 ​ 工作队列的优点: 因工作队列在进程下文中执行,因此工作队列允许重新调度和睡眠,是异步执行的进程上下文。 解决了如果软中断和tasklet执行时间过长会导致系统实时性下降等问题。 (1-1)work_struc

iriczhao的博客 2160
上一篇: 【文本处理】Dele_SpaceTab_eveline
下一篇: android添加新功能有感
shellshell20
博客等级 码龄12年 5粉丝 18原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址