Voglio scaricare un file di grandi dimensioni e gestire contemporaneamente altre cose.Come faccio a gestire le librerie Lua che non fanno coroutine.yield()?
Tuttavia, luasocket.http
non chiama mai coroutine.yield()
. Tutto il resto si blocca mentre il file viene scaricato.
Ecco un esempio illustrativo, in cui cerco di scaricare contemporaneamente un file e stampare alcuni numeri:
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!'
esecuzione produce questo:
1
Downloading large file
FINISHED download (200, 5242880bytes)
2
3
4
5
6
7
8
9
10
FINISHED printing numbers
Both done!
Come si può vedere, printRoutine
è resume
d prima. Stampa il numero 1 e yield
s. Il downloadRoutine
è quindi resume
d, che scarica l'intero file, senza produrre. Solo allora vengono stampati i restanti numeri.
Non voglio scrivere la mia libreria di socket! Cosa posso fare?
Modifica (più tardi lo stesso giorno): Alcuni utenti MUSH have also noticed. Forniscono idee utili.
Le coroutine non sono thread. Non dovresti trattarli come fili. Se un processo non vuole cedere, allora non lo farà, e non puoi * forzarlo * a cedere. LuaSocket ha alcune funzionalità per IO non bloccanti, ma non ho molta familiarità con LuaSocket, quindi dovrai investigarle. –
LuaSocket supporta operazioni asincrone (ovvero non bloccanti). RTFM prima di riscrivere la libreria. – Mud
Fango: Sì, lo "zoccolo" grezzo lo fa. Ma 'socket.http' no. (Vedi http://www.mail-archive.com/[email protected]/msg04969.html.) – Anko