加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

我如何处理没有coroutine.yield()的Lua库?

发布时间:2020-12-14 21:47:39 所属栏目:大数据 来源:网络整理
导读:我想下载一个大文件并同时处理其他事情. 但是, luasocket.http 从不调用coroutine.yield().文件下载时,其他所有内容都会冻结. 这是一个说明性示例,我尝试同时下载文件并打印一些数字: local http = require'socket.http'local downloadRoutine = coroutine.
我想下载一个大文件并同时处理其他事情.

但是,luasocket.http从不调用coroutine.yield().文件下载时,其他所有内容都会冻结.

这是一个说明性示例,我尝试同时下载文件并打印一些数字:

local http = require'socket.http'

local downloadRoutine = coroutine.create(function ()
    print 'Downloading large file'
    -- Download an example file
    local url = 'http://ipv4.download.thinkbroadband.com/5MB.zip'
    local result,status = http.request(url)
    print('FINISHED download ('..status..','..#result..'bytes)')
end)

local printRoutine = coroutine.create(function ()
    -- Print some numbers
    for i=1,10 do
        print(i)
        coroutine.yield()
    end
    print 'FINISHED printing numbers'
end)

repeat
    local printActive = coroutine.resume(printRoutine)
    local downloadActive = coroutine.resume(downloadRoutine)
until not downloadActive and not printActive
print 'Both done!'

运行它会产生这样的:

1
Downloading large file
FINISHED download (200,5242880bytes)
2
3
4
5
6
7
8
9
10
FINISHED printing numbers
Both done!

如您所见,printRoutine首先恢复.它打印数字1和产量.然后恢复downloadRoutine,下载整个文件,而不会屈服.只有这样才能打印其余的数字.

我不想写自己的套接字库!我能做什么?

编辑(当天晚些时候):一些MUSH用户have also noticed.他们提供了有用的想法.

解决方法

我不明白为什么你不能使用 PiL advice或 copas library(这与 here给出的答案几乎相同).

Copas包装套接字接口(不是socket.http),但您可以使用低级接口来获取所需内容(未经测试):

require("socket")
local conn = socket.tcp()
conn:connect("ipv4.download.thinkbroadband.com",80)
conn:send("GET /5MB.zip HTTP/1.1nn")
local file,err = conn:receive()
print(err or file)
conn:close()

然后,您可以使用来自copas的addthread来为您提供一个非阻塞套接字,并使用步/循环函数在有东西可以接收时进行接收.

使用copas的工作量较少,而直接使用settimeout(0)可以提供更多控制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读