consumer #1

Merged
usbharu merged 5 commits from consumer into master 2024-04-03 04:47:45 +00:00
1 changed files with 25 additions and 31 deletions
Showing only changes of commit 68926e3dbd - Show all commits

View File

@ -2,13 +2,12 @@ package dev.usbharu
import dev.usbharu.owl.* import dev.usbharu.owl.*
import io.grpc.ManagedChannelBuilder import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.isActive
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.withLock
import kotlin.math.max import kotlin.math.max
suspend fun main() { suspend fun main() {
@ -30,10 +29,9 @@ suspend fun main() {
this.tasks.addAll(listOf()) this.tasks.addAll(listOf())
}) })
var concurrent = 64 val concurrent = MutableStateFlow(64)
val concurrentMutex = Mutex() val processing = MutableStateFlow(0)
var processing = 0
val processingMutex = Mutex()
coroutineScope { coroutineScope {
launch(Dispatchers.Default) { launch(Dispatchers.Default) {
@ -41,12 +39,13 @@ suspend fun main() {
assignmentTaskServiceCoroutineStub assignmentTaskServiceCoroutineStub
.ready( .ready(
flow { flow {
while (isActive) { while (this@coroutineScope.isActive) {
val andSet = concurrentMutex.withLock {
val andSet = concurrent val andSet = concurrent.getAndUpdate {
concurrent = 0 0
andSet
} }
if (andSet != 0) { if (andSet != 0) {
emit(readyRequest { emit(readyRequest {
this.consumerId = subscribeTask.id this.consumerId = subscribeTask.id
@ -56,19 +55,16 @@ suspend fun main() {
} }
delay(100) delay(100)
val withLock = processingMutex.withLock { concurrent.update {
processing ((64 - it) - processing.value).coerceIn(0, 64 - max(0, processing.value))
}
concurrentMutex.withLock {
concurrent = ((64 - concurrent) - withLock).coerceIn(0, 64 - max(0, withLock))
} }
} }
} }
) )
.onEach { .onEach {
processingMutex.withLock {
processing++ processing.update { it + 1 }
}
try { try {
emit(taskResult { emit(taskResult {
@ -79,14 +75,12 @@ suspend fun main() {
this.success = false this.success = false
}) })
} finally { } finally {
processingMutex.withLock { processing.update { it - 1 }
processing-- concurrent.update {
} if (it < 64) {
concurrentMutex.withLock { it + 1
if (concurrent < 64) {
concurrent++
} else { } else {
concurrent = 64 64
} }
} }
} }