# Coroutines and cancelling blocking code

**URL:** <https://discuss.kotlinlang.org/t/coroutines-and-cancelling-blocking-code/12165>\
**Category:** Libraries\
**Created:** [March 29, 2019, 3:46pm UTC](https://discuss.kotlinlang.org/t/coroutines-and-cancelling-blocking-code/12165 "2019-03-29T15:46:58Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![broot](https://avatars.discourse-cdn.com/v4/letter/b/a88e57/32.png) [@broot](https://discuss.kotlinlang.org/u/broot)\
**Post date:** [March 20, 2022, 12:22pm UTC](https://discuss.kotlinlang.org/t/coroutines-and-cancelling-blocking-code/12165/5 "2022-03-20T12:22:54Z")

</div>

> [@darksnake](#):
>
> `runInterruptible` allows to interrupt a coroutine in a suspesion point or during the `delay` , but not the blocking code.

Doesn’t this depend on whether the blocking operation is interruptible or not? For example, `runInterruptible()` won’t work with `Socket`, but it should with `SocketChannel`. Although, it is a matter of what we mean by “blocking”. As I understand, `SocketChannel` uses non-blocking IO underneath, but it blocks the thread while waiting for IO.

But generally speaking: no, `runInterruptible()` isn’t a bulletproof solution to running synchronous IO.

Some time ago I explored the topic of how to properly handle synchronous IO with coroutines, especially regarding cancellations. I think this topic isn’t very well documented in official docs (?). I found 3 possible solutions:

1. `runInterruptible()` if we know IO is interruptible.
2. Create an utility that automatically closes a resource on cancellation. Something like: [Cancel blocking function after timeout without 'select' - #2 by broot](https://discuss.kotlinlang.org/t/cancel-blocking-function-after-timeout-without-select/24411/2) . This seems like the best solution in most cases, but it requires that we know a resource that is related to the IO operation.
3. Run IO inside a child coroutine and make the parent not wait for it on cancellation. I didn’t find a way to do it properly, but I was able to achieve this with some hacking: [Coroutine/Job that doesn't join its children when cancelled](https://discuss.kotlinlang.org/t/coroutine-job-that-doesnt-join-its-children-when-cancelled/23149)

---

_[View the full topic](https://discuss.kotlinlang.org/t/coroutines-and-cancelling-blocking-code/12165)._
