Coroutine

永井 忠一 2025.12.20


Go と Kotlin

(Goでは、goroutineと名付けられている)

GoKotlin
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

var g_count int64

func main() {
	var wg sync.WaitGroup
	for range 8 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for range 1000000 {
				atomic.AddInt64(&g_count, 1)
			}
		}()
	}
	wg.Wait()
	fmt.Println(g_count)
}

$ go run main.go
8000000
package org.example

import java.util.concurrent.atomic.AtomicLong
//import kotlin.concurrent.atomics.AtomicLong

import kotlinx.coroutines.*

var g_count = AtomicLong(0)

fun main() = runBlocking {
    coroutineScope {
        repeat(8) {
            launch(Dispatchers.Default) {
                repeat(1000000) {
                    g_count.incrementAndGet()
                }
            }
        }
    }
    println(g_count)
}

> Task :org.example.MainKt.main()
8000000

Kotlinでは、executorは、外部ライブラリとして実装されている(「build.gradle.kts」へ、以下を追加)

Gradle
// ...snip...

dependencies {
    // ...snip...
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
}

// ...snip...

© 2025 Tadakazu Nagai