1 /*
2 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5 @file:JvmMultifileClass
6 @file:JvmName("ThreadPoolDispatcherKt")
7 package kotlinx.coroutines
8
9 import kotlin.jvm.*
10
11 /**
12 * Creates a coroutine execution context using a single thread with built-in [yield] support.
13 * **NOTE: The resulting [CloseableCoroutineDispatcher] owns native resources (its thread).
14 * Resources are reclaimed by [CloseableCoroutineDispatcher.close].**
15 *
16 * If the resulting dispatcher is [closed][CloseableCoroutineDispatcher.close] and
17 * attempt to submit a task is made, then:
18 * * On the JVM, the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the
19 * [Dispatchers.IO], so that the affected coroutine can clean up its resources and promptly complete.
20 * * On Native, the attempt to submit a task throws an exception.
21 *
22 * This is a **delicate** API. The result of this method is a closeable resource with the
23 * associated native resources (threads or native workers). It should not be allocated in place,
24 * should be closed at the end of its lifecycle, and has non-trivial memory and CPU footprint.
25 * If you do not need a separate thread-pool, but only have to limit effective parallelism of the dispatcher,
26 * it is recommended to use [CoroutineDispatcher.limitedParallelism] instead.
27 *
28 * If you need a completely separate thread-pool with scheduling policy that is based on the standard
29 * JDK executors, use the following expression:
30 * `Executors.newSingleThreadExecutor().asCoroutineDispatcher()`.
31 * See `Executor.asCoroutineDispatcher` for details.
32 *
33 * @param name the base name of the created thread.
34 */
35 @ExperimentalCoroutinesApi
36 @DelicateCoroutinesApi
newSingleThreadContextnull37 public fun newSingleThreadContext(name: String): CloseableCoroutineDispatcher =
38 newFixedThreadPoolContext(1, name)
39
40 @ExperimentalCoroutinesApi
41 public expect fun newFixedThreadPoolContext(nThreads: Int, name: String): CloseableCoroutineDispatcher
42