123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596(* Copyright (C) 2017 Petter A. Urkedal <paurkedal@gmail.com>
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*)letdefault_max_size=tryint_of_string(Sys.getenv"CAQTI_POOL_MAX_SIZE")withNot_found->8moduleMake(System:Caqti1_system_sig.S)=structopenSystemmoduleTask=structtypet={priority:float;mvar:unitMvar.t}letwake{mvar;_}=Mvar.store()mvarletcompare{priority=pA;_}{priority=pB;_}=Pervasives.comparepBpAendmoduleTaskq=Caqti_heap.Make(Task)type'at={p_create:unit->'aio;p_free:'a->unitio;p_check:'a->(bool->unit)->unit;p_validate:'a->boolio;p_max_size:int;mutablep_cur_size:int;p_pool:'aQueue.t;mutablep_waiting:Taskq.t;}letcreate?(max_size=default_max_size)?(check=fun_f->ftrue)?(validate=fun_->returntrue)createfree={p_create=create;p_free=free;p_check=check;p_validate=validate;p_max_size=max_size;p_cur_size=0;p_pool=Queue.create();p_waiting=Taskq.empty}letsize{p_cur_size;_}=p_cur_sizeletwait~priorityp=letmvar=Mvar.create()inp.p_waiting<-Taskq.pushTask.({priority;mvar})p.p_waiting;Mvar.fetchmvarletrecacquire~priorityp=ifQueue.is_emptyp.p_poolthenbeginifp.p_cur_size<p.p_max_sizethen(p.p_cur_size<-p.p_cur_size+1;p.p_create())else(wait~priorityp>>=fun()->acquire~priorityp)endelsebeginlete=Queue.takep.p_poolincatch(fun()->p.p_validatee)(funxc->Queue.addep.p_pool;failxc)>>=funok->ifokthenreturneelsecatchp.p_create(funxc->p.p_cur_size<-p.p_cur_size-1;failxc)endletreleasepe=p.p_checke@@funok->ifokthenQueue.addep.p_poolelsep.p_cur_size<-p.p_cur_size-1;ifnot(Taskq.is_emptyp.p_waiting)thenlettask,taskq=Taskq.pop_ep.p_waitinginp.p_waiting<-taskq;Task.waketaskletuse?(priority=0.0)fp=acquire~priorityp>>=fune->catch(fun()->fe>>=funr->releasepe;returnr)(funxc->releasepe;failxc)letdisposepe=p.p_freee>>=fun()->p.p_cur_size<-p.p_cur_size-1;return()letrecdrainp=ifp.p_cur_size=0thenreturn()else(ifQueue.is_emptyp.p_poolthenwait~priority:0.0pelsedisposep(Queue.takep.p_pool))>>=fun()->drainpend