Is it safe to close a context inside of a launch (...
# coroutines
l
Is it safe to close a context inside of a launch (at the end)? I have validation in place to ensure this is the final launch that is called and I want the resources held by the context to be freed. If it matters, the context is a
newSingleThreadContext
Copy code
launch(context) {
    doSomething()
    context.close()
}
g
Nothing wrong would happen, but it feels wrong by itself
Why even use a single threaded context in the first place.
l
This is a multiplatform project, so coroutines is the best way to handle multithreading. I need a single threaded context since a library I use is not thread safe, meaning all
launch
calls need to end up on the same thread.
g
But this code launches only one coroutine and after this immediately closes dispatcher
l
I should specify there are other launch calls. There's checks that ensure that this is the last one.
Since no other launch calls will be made, I want the resources of the dispatcher to release.
g
If it's not thread safe doesn't usually mean that it should be on the same thread, only that it should be accessed from multiple threads the same time, if it is the case, you can use coroutine Mutex and wrap library calls
Yes, I understand why you close it, but it's the problem of custom fixed dispatcher, it wastes resources and requires manual close
l
I tried using atomicfu synchronized on a Synchronized object, but was getting crashes. I think the C library I'm calling uses Thread locals or something. When I moved to a single thread context, the crashes seem to go away.
It's not pretty, but the C library I'm using (libav) is pretty famous for crashing easily.
g
But yeah, it may be the case that it requires the same thread