view src/luan/modules/Thread.luan @ 1735:4b56eff90040 default tip

add hosting.html
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 02 Oct 2022 17:32:00 -0600
parents 915cb538e2a3
children
line wrap: on
line source

require "java"
local ThreadLuan = require "java:luan.modules.ThreadLuan"
local ReentrantLock = require "java:java.util.concurrent.locks.ReentrantLock"
local Luan = require "luan:Luan.luan"
local error = Luan.error
local set_metatable = Luan.set_metatable or error()
local Time = require "luan:Time.luan"
local Logging = require "luan:logging/Logging.luan"
local logger = Logging.logger "Thread"


local Thread = {}

Thread.sleep = ThreadLuan.sleep

local function safe(fn)
	return function()
		try
			fn()
		catch e
			logger.error(e)
		end
	end
end
Thread.safe = safe

function Thread.fork(fn)
	fn = safe(fn)
	ThreadLuan.fork(fn)
end

function Thread.schedule(fn,options)
	fn = safe(fn)
	options = options or {}
	ThreadLuan.schedule(fn,options)
end

function Thread.schedule_closure(init_fn,options)
	local function safe_init()
		return safe(init_fn())
	end
	options = options or {}
	ThreadLuan.schedule_closure(safe_init,options)
end


local forever = Time.period{years=100}

function Thread.global_callable(name,init_fn,timeout)
	timeout = timeout or forever
	local callable = ThreadLuan.globalCallable(name,init_fn,timeout)
	local mt = {}
	function mt.__index(_,key)
		return function(...)
			return callable.call(key,...)
		end
	end
	local tbl = {}
	set_metatable(tbl,mt)
	return tbl
end

Thread.remove_global_callable = ThreadLuan.removeGlobalCallable

function Thread.global_map(name,timeout)
	local function init()
		local map = {}
		local fns = {}

		function fns.__index(_,key)
			return map[key]
		end

		function fns.__new_index(_,key,value)
			map[key] = value
		end

		return fns
	end
	local mt = Thread.global_callable(name,init,timeout)
	local tbl = {}
	set_metatable(tbl,mt)
	return tbl
end


local default_time_out = Time.period{minutes=10}
local run_in_lock = ThreadLuan.runInLock
local get_lock = ThreadLuan.getLock

function Thread.synchronized(fn,key,time_out)
	time_out = time_out or default_time_out
	local lock = get_lock(key)
	return function(...)
		return run_in_lock(lock,time_out,fn,...)
	end
end


return Thread