socket lock/unlock

This commit is contained in:
云风
2013-08-22 17:56:20 +08:00
parent 02ff250e02
commit e074076c8d
2 changed files with 37 additions and 6 deletions

View File

@@ -88,7 +88,7 @@ socket_message[4] = function(id, newid, addr)
driver.close(newid) driver.close(newid)
return return
end end
skynet.fork(s.callback, newid, addr) s.callback(newid, addr)
end end
-- SKYNET_SOCKET_TYPE_ERROR = 5 -- SKYNET_SOCKET_TYPE_ERROR = 5
@@ -231,10 +231,38 @@ function socket.listen(host,port,func)
end end
function socket.lock(id) function socket.lock(id)
local s = socket_pool[id]
assert(s)
local lock_set = s.lock
local co = coroutine.running()
if not lock_set then
lock_set = {}
s.lock = lock_set
lock_set[co] = true
elseif next(lock_set) == nil then
lock_set[co] = true
else
assert(lock_set[co] == nil)
lock_set[co] = true
skynet.wait()
end
end end
function socket.unlock(fd) function socket.unlock(id)
local s = socket_pool[id]
assert(s)
local lock_set = s.lock
assert(lock_set)
local co = coroutine.running()
assert(lock_set[co])
lock_set[co] = nil
repeat
co = next(lock_set)
if co == nil then
break
end
lock_set[co] = nil
until skynet.wakeup(co)
end end
return socket return socket

View File

@@ -1,8 +1,7 @@
local skynet = require "skynet" local skynet = require "skynet"
local socket = require "socket" local socket = require "socket"
local function accepter(id, addr) local function accepter(id)
print("connect from " .. addr .. " " .. id)
socket.accept(id) socket.accept(id)
socket.write(id, "Hello Skynet\n") socket.write(id, "Hello Skynet\n")
while true do while true do
@@ -18,5 +17,9 @@ local function accepter(id, addr)
end end
skynet.start(function() skynet.start(function()
socket.listen("127.0.0.1", 8000, accepter) socket.listen("127.0.0.1", 8000, function(id, addr)
print("connect from " .. addr .. " " .. id)
-- you can also call skynet.newservice for this socket id
skynet.fork(accepter, id)
end)
end) end)