@@ -25,6 +25,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
2525import kotlinx.coroutines.flow.StateFlow
2626import kotlinx.coroutines.flow.asStateFlow
2727import kotlinx.coroutines.isActive
28+ import kotlinx.coroutines.sync.Mutex
29+ import kotlinx.coroutines.sync.withLock
2830import kotlinx.coroutines.withContext
2931import org.tensorflow.lite.DataType
3032import org.tensorflow.lite.Interpreter
@@ -47,6 +49,7 @@ class ImageSegmentationService(private val context: Context) {
4749 val segmentation: StateFlow <SegmentationResult ?> = _segmentation .asStateFlow()
4850
4951 private var interpreter: Interpreter ? = null
52+ private val inferenceLock = Mutex ()
5053
5154 fun initialize () {
5255 interpreter = try {
@@ -83,18 +86,19 @@ class ImageSegmentationService(private val context: Context) {
8386 return SegmentationResult (segmentResult, inferenceTime)
8487 }
8588
86- fun runSegmentationAndReturn (bitmap : Bitmap , rotationDegrees : Int ): SegmentationResult ? {
87- if (interpreter != null ) {
88- return runSegmentation(interpreter!! , bitmap, rotationDegrees)
89+ suspend fun runSegmentationAndReturn (bitmap : Bitmap , rotationDegrees : Int ): SegmentationResult ? {
90+ if (interpreter == null ) {
91+ return null
92+ }
93+ return inferenceLock.withLock {
94+ runSegmentation(interpreter!! , bitmap, rotationDegrees)
8995 }
90- return null
9196 }
9297
9398 suspend fun runSegmentationAndEmit (bitmap : Bitmap , rotationDegrees : Int ) {
94- if (interpreter == null ) return
9599 try {
96100 withContext(Dispatchers .IO ) {
97- val segmentationResult = runSegmentation(interpreter !! , bitmap, rotationDegrees)
101+ val segmentationResult = runSegmentationAndReturn( bitmap, rotationDegrees)
98102 if (isActive) {
99103 _segmentation .value = segmentationResult
100104 }
0 commit comments