Torch Threads

最近在读openface源码的时候,对里面的线程不怎么清楚。然后就到github上读了下说明。

  • Markdown和扩展Markdown简洁的语法
  • 代码块高亮
  • 图片链接和图片上传
  • LaTex数学公式
  • UML序列图和流程图
  • 离线写博客
  • 导入导出Markdown文件
  • 丰富的快捷键

简介

你可能会想为什么另外开发一个基于lua的线程包?其实就我所知,目前存在的线程包作用十分有限,仅仅是创建线程,线程完成任务,结束线程这么简单。每当我想要使用线程完成某项任务的时候,总是创建线程的开销就远大于了我的工作量。而且在线程之间传递数据也非常不方便。torch提供的threads包有以下优点。

  • 线程只被创建一次,其实就是使用线程池。加粗 Ctrl + B
  • 任务以回调函数的形式传入线程系统,传入的回调函数将会被线程池空闲的线程执行。斜体 Ctrl + I
  • 如果提供的有结束回调函数,那么在任务完成(回调函数执行完毕)之后将在主函数中执行结束回调函数。引用 Ctrl + Q
  • 任务执行的时候是完全序列化的,允许线程之间进行数据copy。插入链接 Ctrl + L
  • 回调函数返回的值将会传入结束回调函数中。插入代码 Ctrl + K
  • 在结束回调函数中,可以直接使用主线程中的变量。插入图片 Ctrl + G
  • 线程间的同步操作非常简便。提升标题 Ctrl + H

代码块

local threads = require 'threads'local nthread = 4
local njob = 10
local msg = "hello from a satellite thread"local pool = threads.Threads(nthread,function(threadid)print('starting a new thread/state number ' .. threadid)gmsg = msg -- get it the msg upvalue and store it in thread stateend
)local jobdone = 0
for i=1,njob dopool:addjob(function()print(string.format('%s -- thread ID is %x', gmsg, __threadid))return __threadidend,function(id)print(string.format("task %d finished (ran on thread ID %x)", i, id))jobdone = jobdone + 1end)
endpool:synchronize()print(string.format('%d jobs done', jobdone))pool:terminate()

通过阅读上面的说明,我以为在回调函数中无法访问主线程中的变量i,但是通过实例发现在回调函数和结束回调函数中都可访问主线程中的变量i,此外确定了一点,回调函数和结束回调函数都是被线程池里面的线程执行的,任何一方都不是被主线程执行的。而且每个回调函数和结束回调函数合并在一起作为任务被某个线程进行处理,在从回调函数到结束回调函数转换的过程中,并没有进行线程切换。
上面的代码通过threads.Threads创建了一个线程池。在pool:addjob里面加入要执行的回调函数和结束回调函数。pool:synchronize()简简单单一句代码就维持了线程之间的同步。pool:terminate()进行线程资源释放,应该是在所有任务都结束的时候,就会自动释放资源。

运行结果

starting a new thread/state number 1
starting a new thread/state number 3
starting a new thread/state number 2
starting a new thread/state number 4
hello from a satellite thread – thread ID is 1
hello from a satellite thread – thread ID is 2
hello from a satellite thread – thread ID is 1
hello from a satellite thread – thread ID is 2
hello from a satellite thread – thread ID is 4
hello from a satellite thread – thread ID is 2
hello from a satellite thread – thread ID is 1
hello from a satellite thread – thread ID is 3
task 1 finished (ran on thread ID 1)
hello from a satellite thread – thread ID is 4
task 2 finished (ran on thread ID 2)
hello from a satellite thread – thread ID is 4
task 3 finished (ran on thread ID 1)
task 4 finished (ran on thread ID 2)
task 5 finished (ran on thread ID 4)
task 9 finished (ran on thread ID 4)
task 10 finished (ran on thread ID 4)
task 8 finished (ran on thread ID 3)
task 6 finished (ran on thread ID 2)
task 7 finished (ran on thread ID 1)
10 jobs done

  • Torch Threads

    • 简介

      • 代码块
      • 运行结果
      • Library
      • Threads

Library

library 提供了不同级别的线程功能。

  • 中级的功能:
  • Threads线程池、Queue线程队列、serialize序列化和反序列化线程、safe()创建一个安全的线程。
  • 低级的功能:
  • Thread创建一个简单的线程。Mutex创建自旋锁。Condition创建一个条件变量。Atomic counter 原子锁。

Threads:

threads包里面被threads.Threads()创建的类作用非常大,后面还可以做更高级功能的封装。
这个类一般都这样来用:

local threads = require 'threads'
local t = threads.Threads(4) -- create a pool of 4 threads

但是在之前的threads包里面只有一个类,一般都这样创建。

local Threads = require 'threads'
local t = Threads(4) -- create a pool of 4 threads

一个线程池里面一般都会管理好几个队列,后面介绍的基本上都是线程池内线程和任务的管理,比如从任务队列里面获取任务,以及线程结束后如何从回调函数传入到结束回调函数最后再进入主线程。

require 'nn'
local threads = require 'threads'
local model = nn.Linear(5, 10)
threads.Threads(2,function(idx)                       -- This code will crashrequire 'nn'                    -- because the upvalue 'model' local myModel = model:clone()   -- is of unknown type before deserializationend
)
require 'nn'
local threads = require 'threads'
local model = nn.Linear(5, 10)
threads.Threads(2,function(idx)                      -- This code is OK.require 'nn'end,                               -- child threads know nn.Linear when deserializing f2function(idx)local myModel = model:clone()  -- because f1 has already been executedend
)

threads.Threads(N,[f1,f2,…])在创建线程池的时候,可传入多个参数,一般都会在f1放入定义,而在后面的函数中放入代码。

Torch Threads相关推荐

  1. 学习笔记CB012: LSTM 简单实现、完整实现、torch、小说训练word2vec lstm机器人

    摘要: 真正掌握一种算法,最实际的方法,完全手写出来. LSTM(Long Short Tem Memory)特殊递归神经网络,神经元保存历史记忆,解决自然语言处理统计方法只能考虑最近n个词语而忽略更 ...

  2. pytorch分布式训练(一):torch.nn.DataParallel

      本文介绍最简单的pytorch分布式训练方法:使用torch.nn.DataParallel这个API来实现分布式训练.环境为单机多gpu,不妨假设有4个可用的gpu. 一.构建方法 使用这个AP ...

  3. torch.nn、(二)

    参考 torch.nn.(二) - 云+社区 - 腾讯云 目录 Recurrent layers RNN LSTM GRU RNNCell LSTMCell GRUCell Transformer l ...

  4. Pyinstaller 打包 torch 后执行失败 OSError: could not get source code

    1. 问题现象 系统环境 Python 3.6.9 torch 1.2.0 torchvision 0.4.0 Pyinstaller 4.5.1 Pyinstaller 打包 torch 后执行失败 ...

  5. torch.nn.functional.cross_entropy.ignore_index

    ignore_index表示计算交叉熵时,自动忽略的标签值,example: import torch import torch.nn.functional as F pred = [] pred.a ...

  6. torch.backends.cudnn.deterministic 使用cuda保证每次结果一样

    为什么使用相同的网络结构,跑出来的效果完全不同,用的学习率,迭代次数,batch size 都是一样?固定随机数种子是非常重要的.但是如果你使用的是PyTorch等框架,还要看一下框架的种子是否固定了 ...

  7. PyTorch的torch.cat

    字面理解:torch.cat是将两个张量(tensor)拼接在一起,cat是concatnate的意思,即拼接,联系在一起. 例子理解 import torch A=torch.ones(2,3) # ...

  8. pytorch学习 中 torch.squeeze() 和torch.unsqueeze()的用法

    squeeze的用法主要就是对数据的维度进行压缩或者解压. 先看torch.squeeze() 这个函数主要对数据的维度进行压缩,去掉维数为1的的维度,比如是一行或者一列这种,一个一行三列(1,3)的 ...

  9. PyTorch里面的torch.nn.Parameter()

    在刷官方Tutorial的时候发现了一个用法self.v = torch.nn.Parameter(torch.FloatTensor(hidden_size)),看了官方教程里面的解释也是云里雾里, ...

最新文章

  1. MongoDB分布式原理以及read-preference和readConcern解决读写一致性问题
  2. 如何使用JavaScript Math.floor生成范围内的随机整数-已解决
  3. android多线程文章,Android 多线程处理之多线程用法大集合
  4. 使用ConnectivityManager 判断网络是否连接
  5. MySQL__数据处理之查询
  6. python isnumberic用法_NETASST技术博客
  7. 手把手教你修改iOS版QQ的运动步数
  8. Access denied for user ‘bijian0530‘@‘localhost‘ (using password: YES)
  9. WORD打印时显示错误,未定义标签?
  10. 目前国内的跨境收款通道有哪些还不错的?
  11. html5学生作业简单源代码,html5 简单实例源代码
  12. access查找出生日期年份_access查询最大年龄减最小年龄
  13. 使用Oracle数据库的一些小记录 1
  14. 联想ThinkServer RS260服务器静音降噪改造及CentOS拷机测试
  15. uniapp兼容iPhoneX头部状态栏(刘海屏)和底部小横条
  16. Oracle建表——图书表
  17. 从零开始安装搭建win10与ubuntu20.04双系统开发环境——集安装、配置、软件、美化、常见问题等于一体的——超详细教程
  18. Windows中更改ctrl与alt键互换位置
  19. 如何通过平台注册到过期域名?
  20. char* char[] string

热门文章

  1. 电脑网易云音乐,拿下华研,网易云音乐终于解决1%的大难题,可阿里音乐以后咋办?...
  2. Unity实现边录边播
  3. Selenium屏幕截图教程
  4. centos7 mailx 邮件发送163邮箱 第二种方式
  5. ROS1 LTS版本安装教程
  6. JDK 8 List集合使用记录
  7. 【转】Parallelism in PostgreSQL
  8. 服务器和普通的PC机的区别有哪些
  9. Inno Setup 常用代码
  10. jira中新增模块详解