From e074076c8df19ac17870b3bb81fc95b6148c07fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=91=E9=A3=8E?= Date: Thu, 22 Aug 2013 17:56:20 +0800 Subject: [PATCH] socket lock/unlock --- lualib/socket.lua | 34 +++++++++++++++++++++++++++++++--- service/testsocket.lua | 9 ++++++--- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/lualib/socket.lua b/lualib/socket.lua index 8937dd85..fc075f9f 100644 --- a/lualib/socket.lua +++ b/lualib/socket.lua @@ -88,7 +88,7 @@ socket_message[4] = function(id, newid, addr) driver.close(newid) return end - skynet.fork(s.callback, newid, addr) + s.callback(newid, addr) end -- SKYNET_SOCKET_TYPE_ERROR = 5 @@ -231,10 +231,38 @@ function socket.listen(host,port,func) end 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 -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 return socket diff --git a/service/testsocket.lua b/service/testsocket.lua index 8c452e2e..3e77b27d 100644 --- a/service/testsocket.lua +++ b/service/testsocket.lua @@ -1,8 +1,7 @@ local skynet = require "skynet" local socket = require "socket" -local function accepter(id, addr) - print("connect from " .. addr .. " " .. id) +local function accepter(id) socket.accept(id) socket.write(id, "Hello Skynet\n") while true do @@ -18,5 +17,9 @@ local function accepter(id, addr) end 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)