简体   繁体   English

GlobalScope.launch(Main) 中的同步函数:Kotlin

[英]Synchronise function inside GlobalScope.launch(Main): Kotlin

Scenerio: let fun A() and fun B() be two functions. Scenerio:让fun A()fun B()成为两个函数。 Inside A() we are calling B( ).A()我们调用B( )。 B() execution time takes around 5sec and meanwhile some other thread call A() again, then I am getting ConcurrentModificationException . B()执行时间大约需要 5 秒,同时其他一些线程再次调用 A(),然后我得到ConcurrentModificationException

fun A(){
  GlobalScope.launch(Main) {
    val result = withContext(IO) {
      B()
    }
    if (this@activity.isValid()) {
      suggestedFeedItems = result
    } else {

    }
  }
} 

fun B(){
   //some code that takes some time to execute
}

How to synchronise it so that at a time one thread can execute B().如何同步它以便一次一个线程可以执行 B()。 I already tried to use @synchronise .我已经尝试使用@synchronise As im new in kotlin, Please suggest.由于我是 kotlin 的新手,请提出建议。

Problem seems to be exist in fun B() , where you might be doing loop in some Collection type (sa List, Stack...) and also deleting/inserting new element to that Collection type.问题似乎存在于fun B() ,您可能会在某些Collection类型(sa 列表、堆栈...)中执行循环,并且还向该集合类型删除/插入新元素。

If that is the case, you should use Iterator to loop and you can delete/insert items while iterating.如果是这种情况,您应该使用Iterator进行循环,并且您可以在迭代时删除/插入项目。 But if one thread is looping and other thread is inserting/deleting items, you need to synchronize access to that Collection type (using @Synchronized fun B() etc...).但是如果一个线程在循环而另一个线程正在插入/删除项目,则需要同步对该集合类型的访问(使用@Synchronized fun B()等...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在jetpack compose中替换GlobalScope.launch - replace GlobalScope.launch in jetpack compose GlobalScope.launch 是“微妙的” - 如何处理? - GlobalScope.launch is "delicate" - how to deal with? 为什么 Kotlin 中某些 GlobalScope.launch 调用的内容默默地无法执行? - Why are the contents of some GlobalScope.launch calls in Kotlin silently failing to execute? view.post() 和 GlobalScope.launch(Dispatchers.Main) 有什么区别? - What's the difference between view.post() and GlobalScope.launch(Dispatchers.Main)? 使用 GlobalScope.launch 和 CoroutineScope().launch 启动协程有区别吗? - Is there a difference between using GlobalScope.launch and CoroutineScope().launch to launch a coroutine? 使用协程时使用 GlobalScope.launch 的效果 - Effect of using GlobalScope.launch while using coroutine 如何从“GlobalScope.launch”块获取字符串作为返回值 - How to get String as a return value from "GlobalScope.launch" block Kotlin 的 GlobalScope (Coroutine) 中的代码无法正常工作 - Code inside Kotlin's GlobalScope (Coroutine) is not working properly 使用GlobalScope的Kotlin SQL调用 - Kotlin SQL calls using GlobalScope Kotlin 协程 GlobalScope 文档清晰 - Kotlin Coroutine GlobalScope documentation clarity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM