lua的并发哲学

lua的并发哲学
实现并发:1、多线程(本质是共享内存数据、所以要同步多线程) 2、协程(本质是单线程、需要保证不阻塞)

协程的好处:
1、不用线程调度所以可以更充分利用cpu、
2、不处理线程同步减少bug、
3、不会为了效率而故意打断逻辑上一致的代码块(所有有IO的地方后续的代码都要放在回调里),
虚拟机内部在IO函数上yield和resume,回调对用户是屏蔽的

缺点:一个协程阻塞会堵住所有的协程,所以要特殊处理IO

协程体系下的调度器:简单的顺序调度就可以有很高的吞吐率。

一个示例性框架
threads = {} --可以被调度的协程

function receive(connection)
connection:settimeout(0) -----使得receive调用不会阻塞
local s, status,partial = connection:receive(2^10)
if status == "timeout" then
coroutine.yield(connection)-------让出协程
end
return s or partial, status
end

function download(host, file)
local c = assert(socket.connect(host,80))
local count = 0 ---收到的字节数
c:send("GET" ..file.. "HTTP/1.0\r\n\r\n")
while true do
local s,status,partial = receive(c)
count = count + #(s or partial)
if status == "closed" then break end ------读取结束就退出
end
c:close()
print(file, count)
end

function get(host, file)
---
local co = coroutine.create(function()
download(host,file)
end)

----
table.insert(threads, co)
end

function dispatch()
local i = 1
while true do
local status, res = coroutine.resume(threads[i])
if not res then
table.remove(threads, i)
else
i = i+1
end
end
end

客户端使用

get(host,"html40.txt")
get(host,"html40.txt")

dispatch()


全脚本服务器的架构

内核:纯c实现的解释器、提供协程调度、io异步等功能(多个c线程分别处理IO、逻辑运算),并发的c线程中,网络来的消息,放入适当的coroutine内部队列中

主线程:进行tick循环,每一次的tick依次调度各个coroutine,

一个tick的逻辑:
更新每个coroutine的消息队列(从脚本内核的内部队列映射到coroutine自己的消息队列)
依次服务每个消息

开源server端框架:copas
http://keplerproject.github.com/copas/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值