Add lock for TemporaryPacketHandlers

This commit is contained in:
Him188 2019-10-15 19:04:29 +08:00
parent f9daee0379
commit fb8829a035

View File

@ -1,6 +1,8 @@
package net.mamoe.mirai.network.protocol.tim package net.mamoe.mirai.network.protocol.tim
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.io.core.* import kotlinx.io.core.*
import net.mamoe.mirai.* import net.mamoe.mirai.*
import net.mamoe.mirai.event.EventScope import net.mamoe.mirai.event.EventScope
@ -30,12 +32,15 @@ internal class TIMBotNetworkHandler internal constructor(private val bot: Bot) :
override lateinit var socket: BotSocket override lateinit var socket: BotSocket
internal val temporaryPacketHandlers = mutableListOf<TemporaryPacketHandler<*>>() internal val temporaryPacketHandlers = mutableListOf<TemporaryPacketHandler<*>>()
private val handlersLock = Mutex()
private var heartbeatJob: Job? = null private var heartbeatJob: Job? = null
override suspend fun addHandler(temporaryPacketHandler: TemporaryPacketHandler<*>) { override suspend fun addHandler(temporaryPacketHandler: TemporaryPacketHandler<*>) {
temporaryPacketHandlers.add(temporaryPacketHandler) handlersLock.withLock {
temporaryPacketHandlers.add(temporaryPacketHandler)
}
temporaryPacketHandler.send(this[ActionPacketHandler].session) temporaryPacketHandler.send(this[ActionPacketHandler].session)
} }
@ -170,8 +175,10 @@ internal class TIMBotNetworkHandler internal constructor(private val bot: Bot) :
packet.use { packet.use {
//coz removeIf is not inline //coz removeIf is not inline
temporaryPacketHandlers.removeIfInlined { handlersLock.withLock {
it.onPacketReceived(this@TIMBotNetworkHandler[ActionPacketHandler].session, packet) temporaryPacketHandlers.removeIfInlined {
it.onPacketReceived(this@TIMBotNetworkHandler[ActionPacketHandler].session, packet)
}
} }
val name = packet::class.simpleName val name = packet::class.simpleName