paranid5

pool.kt

Jun 22nd, 2021 (edited)
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.30 KB | None | 0 0
  1. import java.io.*
  2. import java.util.*
  3. import java.util.concurrent.LinkedBlockingQueue
  4.  
  5. private class ThreadPool<T>(
  6.     threadsAmount: Int,
  7.     action: (T) -> Unit
  8. ) : Closeable {
  9.     private val actionThreads = Array(threadsAmount) {
  10.         Thread {
  11.             while (working || !taskQueue.isEmpty()) {
  12.                 val v = taskQueue.poll()
  13.                 if (v != null) action(v)
  14.             }
  15.         }
  16.     }
  17.  
  18.     private val taskQueue: Queue<T> = LinkedBlockingQueue()
  19.  
  20.     @Volatile
  21.     private var working = false
  22.  
  23.     fun start() {
  24.         working = true
  25.         actionThreads.forEach(Thread::start)
  26.     }
  27.  
  28.     fun push(elem: T) = taskQueue.offer(elem)
  29.  
  30.     override fun close() {
  31.         working = false
  32.     }
  33. }
  34.  
  35. private fun fib(number: Int): Int {
  36.     if (number < 3)
  37.         return 1
  38.  
  39.     var f = 1
  40.     var s = 1
  41.  
  42.     (3..number).forEach { _ ->
  43.         val mem = s
  44.         s += f
  45.         f = mem
  46.     }
  47.  
  48.     return s
  49. }
  50.  
  51. fun main() = System.`in`.bufferedReader().use { reader ->
  52.     print("Threads amount: ")
  53.  
  54.     ThreadPool<Int>(reader.readLine().toInt()) { println(fib(it)) }.use { pool ->
  55.         File("file.txt").bufferedReader().use { fileReader ->
  56.             pool.start()
  57.             fileReader.lines().forEach { pool.push(it.toInt()) }
  58.         }
  59.     }
  60. }
Add Comment
Please, Sign In to add comment