1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Introduces a minimal ThreadPool implementation using Tasks
18 intrude import pthreads
19 import concurrent_collections
21 # A simple ThreadPool implemented with an array
23 private var queue
= new ConcurrentList[JoinTask].wrap
(new List[JoinTask])
24 private var mutex
= new Mutex
25 private var cond
= new NativePthreadCond
27 # Number of threads used
28 var nb_threads
: Int is noinit
31 for i
in [0..nb_threads
[ do
32 var t
= new PoolThread(queue
, mutex
, cond
)
37 private fun set_nb_threads
(nb
: nullable Int) is autoinit
do nb_threads
= nb
or else 5
39 # Adds a Task into the queue
40 fun execute
(task
: JoinTask) do
46 # A Thread running in a threadpool
47 private class PoolThread
50 var queue
: ConcurrentList[JoinTask]
52 var cond
: NativePthreadCond
56 var t
: nullable JoinTask = null
58 if queue
.is_empty
then cond
.wait
(mutex
.native
.as(not null))
59 if not queue
.is_empty
then
68 if tcond
!= null then tcond
.signal
75 # A Task which is joinable, meaning it can return a value and if the value is not set yet, it blocks the execution
82 private var mutex
= new Mutex
83 private var cond
: nullable NativePthreadCond = null
85 # Return immediatly if the task terminated, or block waiting for `self` to terminate
89 var cond
= new NativePthreadCond
91 cond
.wait
(mutex
.native
.as(not null))