如何巧妙应对缺乏coroutine.yield()功能的Lua库挑战?
- 内容介绍
- 文章标签
- 相关推荐
本文共计428个文字,预计阅读时间需要2分钟。
我想要下载一个大文件并同时处理其他事务,但luasocket.http没有调用coroutine.yield()。在文件下载时,其他所有内容都会冻结。这是一个说明性示例,我尝试同时下载文件并打印一些数字:loc
我想下载一个大文件并同时处理其他事情.但是, 运行它会产生这样的: 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.他们提供了有用的想法. Copas包装套接字接口(不是socket.http),但您可以使用低级接口来获取所需内容(未经测试):luasocket.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!'
require("socket") local conn = socket.tcp() conn:connect("ipv4.download.thinkbroadband.com", 80) conn:send("GET /5MB.zip HTTP/1.1\n\n") local file, err = conn:receive() print(err or file) conn:close()
然后,您可以使用来自copas的addthread来为您提供一个非阻塞套接字,并使用步/循环函数在有东西可以接收时进行接收.
使用copas的工作量较少,而直接使用settimeout(0)可以提供更多控制.
本文共计428个文字,预计阅读时间需要2分钟。
我想要下载一个大文件并同时处理其他事务,但luasocket.http没有调用coroutine.yield()。在文件下载时,其他所有内容都会冻结。这是一个说明性示例,我尝试同时下载文件并打印一些数字:loc
我想下载一个大文件并同时处理其他事情.但是, 运行它会产生这样的: 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.他们提供了有用的想法. Copas包装套接字接口(不是socket.http),但您可以使用低级接口来获取所需内容(未经测试):luasocket.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!'
require("socket") local conn = socket.tcp() conn:connect("ipv4.download.thinkbroadband.com", 80) conn:send("GET /5MB.zip HTTP/1.1\n\n") local file, err = conn:receive() print(err or file) conn:close()
然后,您可以使用来自copas的addthread来为您提供一个非阻塞套接字,并使用步/循环函数在有东西可以接收时进行接收.
使用copas的工作量较少,而直接使用settimeout(0)可以提供更多控制.

