Skip to content

M0206: Object leaves the thread but its allocator is not ThreadSafe ​

error

What it means ​

A value from an allocator that does not implement ThreadSafe (Arena, Pool), or the allocator itself, is captured by a thread lambda (spawn { }).

Minimal failing example ​

From the test corpus: compiler/testdata/memory/thread_nonsafe.kt. The corpus expects 14:27: M0206 (the ^ comment in the source marks the column).

kotlin
// REJECT M0206: an object of a non-ThreadSafe allocator (Pool) crosses into a thread. Spec 5.9, 7.17
@file:MemoryMode(Mode.Strict)

package memory.thread_nonsafe

import mini.memory.*

class Item(val id: Int)

fun main() {
    Pool<Item>(2).use { pool ->
        context(pool) {
            val item = Item(1)
            val t = spawn {
//                        ^ M0206
                println(item.id)
                item.free()
            }
            t.join()
        }
    }
}

Compiler output ​

Generated by running ./minic check compiler/testdata/memory/thread_nonsafe.kt (exit status 1).

text
$ ./minic check compiler/testdata/memory/thread_nonsafe.kt
error[M0206]: `Pool` is not ThreadSafe: `item` cannot cross a thread boundary
  --> compiler/testdata/memory/thread_nonsafe.kt:14:27   captured here
   14 |             val t = spawn {
      |                           ^
  help: use a `Heap` allocator

note: M0206 (Object leaves the thread but its allocator is not ThreadSafe): https://henryschwerdt.github.io/mini/reference/diagnostics/M0206

error: could not compile thread_nonsafe.kt (1 error, 0 warnings)

How to fix ​

Allocate the shared objects from a Heap, which is ThreadSafe.

Corpus programs for this code ​

See also: Diagnostics overview and the memory guide.

Released under the Apache License 2.0.