comparison app/src/main/java/com/bartsent/simpleresizer/lib/Channel.kt @ 9:884092efe31a concur

Gets gratuitously killed. WTF?
author David Barts <n5jrn@me.com>
date Wed, 17 Feb 2021 13:20:25 -0800
parents 9374d044a132
children
comparison
equal deleted inserted replaced
7:9374d044a132 9:884092efe31a
1 package com.bartsent.simpleresizer.lib 1 package com.bartsent.simpleresizer.lib
2 2
3 import android.util.Log
3 import java.util.concurrent.Semaphore 4 import java.util.concurrent.Semaphore
4 5
5 /** 6 /**
6 * A typed, buffered communications channel a'la C.A.R. Hoare's communicating sequential 7 * A typed, buffered communications channel a'la C.A.R. Hoare's communicating sequential
7 * processes (CSP). 8 * processes (CSP).
15 /** 16 /**
16 * Write a single item to this channel. 17 * Write a single item to this channel.
17 * @param item Item to write 18 * @param item Item to write
18 */ 19 */
19 fun write(item: T): Unit { 20 fun write(item: T): Unit {
21 Log.d("Channel<${hashCode()}>", "write…")
20 wSem.acquire() 22 wSem.acquire()
21 synchronized(this) { 23 synchronized(this) {
22 buffer[(start + rSem.availablePermits()) % buffer.size] = item 24 buffer[(start + rSem.availablePermits()) % buffer.size] = item
23 rSem.release() 25 rSem.release()
24 } 26 }
27 Log.d("Channel<${hashCode()}>", "write done")
25 } 28 }
26 29
27 /** 30 /**
28 * Read a single item from this channel. 31 * Read a single item from this channel.
29 * @return The item read 32 * @return The item read
30 */ 33 */
31 fun read(): T { 34 fun read(): T {
35 Log.d("Channel<${hashCode()}>", "read…")
32 rSem.acquire() 36 rSem.acquire()
33 synchronized(this) { 37 synchronized(this) {
34 val ret = buffer[start]!! as T 38 val ret = buffer[start]!! as T
35 buffer[start] = null // unref 39 buffer[start] = null // unref
36 start = (start + 1) % buffer.size 40 start = (start + 1) % buffer.size
37 wSem.release() 41 wSem.release()
42 Log.d("Channel<${hashCode()}>", "read done")
38 return ret 43 return ret
39 } 44 }
40 } 45 }
41 } 46 }