Advertisement
paranid5

CV

Jun 1st, 2021 (edited)
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.45 KB | None | 0 0
  1. import java.io.File
  2. import java.util.concurrent.locks.ReentrantLock
  3. import kotlin.concurrent.thread
  4. import kotlin.concurrent.withLock
  5.  
  6. private fun <T : Number> T.fib(): Long {
  7.     if (this.toLong() < 3) return 1
  8.  
  9.     var f = 1L
  10.     var s = 1L
  11.     val long = this.toLong()
  12.  
  13.     (3..long).forEach { _ ->
  14.         val mem = s
  15.         s += f
  16.         f = mem
  17.     }
  18.  
  19.     return s
  20. }
  21.  
  22. fun main() {
  23.     val lock = ReentrantLock()
  24.     val noDataCondition = lock.newCondition()
  25.     val container = ArrayDeque<String?>()
  26.  
  27.     val adder = thread {
  28.         File("file.txt").forEachLine {
  29.             lock.withLock {
  30.                 while (container.size >= 100)
  31.                     noDataCondition.await()
  32.                 container.add(it)
  33.                 noDataCondition.signalAll()
  34.             }
  35.  
  36.             Thread.sleep(10)
  37.         }
  38.  
  39.         lock.withLock(noDataCondition::signalAll)
  40.     }
  41.  
  42.     (0..3).forEach { _ ->
  43.         thread {
  44.             while (adder.isAlive) {
  45.                 lock.withLock {
  46.                     while (container.isEmpty()) {
  47.                         if (!adder.isAlive) break
  48.                         noDataCondition.await()
  49.                     }
  50.  
  51.                     if (!adder.isAlive) return@withLock
  52.  
  53.                     println(container.removeFirst()!!.toLong().fib())
  54.                     noDataCondition.signal()
  55.                 }
  56.  
  57.                 if (!adder.isAlive) break
  58.             }
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement