oneoo / alilua-coevent-module

epoll base coroutine module

Home Page:http://alilua.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

httpclient with multi loop

pahud opened this issue · comments

您好,請問我的代碼

local L = require('coevent')
local httpc = require('httpclient')

local function test_case(test_id)
        local res, err = httpc.httprequest('http://sina.com')
        return #res.body
end

L(function()
        local t1 = newthread(test_case, 1)
        local t2 = newthread(test_case, 2)
        print(coroutine_wait(t1))
        print(coroutine_wait(t2))
end)

執行的時候有時候第二個thread會返回true

vm:~$ lua c.lua 
184
true

但有時候卻不會

vm:~$ lua c.lua 
184
184

請問這是什麼原因?

你要捕获 err 输出,看看具体的错误

知道原因了,是wait(thread)时,该 thread 已完成,导致结果无法捕捉,而返回了 true。
建议更改写法为:

local L = require('coevent')
local httpc = require('httpclient')

local results = {}
local function test_case(test_id)
        local res, err = httpc.httprequest('http://sina.com')
        results[test_id] = #res.body
        return #res.body
end

L(function()
        local t1 = newthread(test_case, 1)
        local t2 = newthread(test_case, 2)
        print(wait(t1))
        print(wait(t2))

        for k,v in pairs(results) do
            print(k,v)
        end
end)

原來如此,非常感謝!