Comparison

net/server_select.lua @ 6481:dbc72cd1332e

Move timer code out of util.timer and into relevant net.server backends
author daurnimator <quae@daurnimator.com>
date Mon, 20 Oct 2014 16:13:24 -0400
parent 6465:ab68bb837fe0
child 6539:f923140ee7c5
comparison
equal deleted inserted replaced
6480:37b12475f648 6481:dbc72cd1332e
40 40
41 local os_difftime = os.difftime 41 local os_difftime = os.difftime
42 local math_min = math.min 42 local math_min = math.min
43 local math_huge = math.huge 43 local math_huge = math.huge
44 local table_concat = table.concat 44 local table_concat = table.concat
45 local table_insert = table.insert
45 local string_sub = string.sub 46 local string_sub = string.sub
46 local coroutine_wrap = coroutine.wrap 47 local coroutine_wrap = coroutine.wrap
47 local coroutine_yield = coroutine.yield 48 local coroutine_yield = coroutine.yield
48 49
49 --// extern libs //-- 50 --// extern libs //--
830 _timerlistlen = _timerlistlen + 1 831 _timerlistlen = _timerlistlen + 1
831 _timerlist[ _timerlistlen ] = listener 832 _timerlist[ _timerlistlen ] = listener
832 return true 833 return true
833 end 834 end
834 835
836 local add_task do
837 local data = {};
838 local new_data = {};
839
840 function add_task(delay, callback)
841 local current_time = luasocket_gettime();
842 delay = delay + current_time;
843 if delay >= current_time then
844 table_insert(new_data, {delay, callback});
845 else
846 local r = callback(current_time);
847 if r and type(r) == "number" then
848 return add_task(r, callback);
849 end
850 end
851 end
852
853 addtimer(function()
854 local current_time = luasocket_gettime();
855 if #new_data > 0 then
856 for _, d in pairs(new_data) do
857 table_insert(data, d);
858 end
859 new_data = {};
860 end
861
862 local next_time = math_huge;
863 for i, d in pairs(data) do
864 local t, callback = d[1], d[2];
865 if t <= current_time then
866 data[i] = nil;
867 local r = callback(current_time);
868 if type(r) == "number" then
869 add_task(r, callback);
870 next_time = math_min(next_time, r);
871 end
872 else
873 next_time = math_min(next_time, t - current_time);
874 end
875 end
876 return next_time;
877 end);
878 end
879
835 stats = function( ) 880 stats = function( )
836 return _readtraffic, _sendtraffic, _readlistlen, _sendlistlen, _timerlistlen 881 return _readtraffic, _sendtraffic, _readlistlen, _sendlistlen, _timerlistlen
837 end 882 end
838 883
839 local quitting; 884 local quitting;
1005 1050
1006 ----------------------------------// PUBLIC INTERFACE //-- 1051 ----------------------------------// PUBLIC INTERFACE //--
1007 1052
1008 return { 1053 return {
1009 _addtimer = addtimer, 1054 _addtimer = addtimer,
1055 add_task = add_task;
1010 1056
1011 addclient = addclient, 1057 addclient = addclient,
1012 wrapclient = wrapclient, 1058 wrapclient = wrapclient,
1013 1059
1014 loop = loop, 1060 loop = loop,