[K/N][Runtime] Switch thread states in termination handlers

This commit is contained in:
Ilya Matveev
2021-07-19 20:14:14 +07:00
committed by Space
parent a1f6c70355
commit 99bd26c2ef
15 changed files with 536 additions and 126 deletions
@@ -1,3 +1,4 @@
#include <future>
#include <thread>
#include <stdint.h>
#include <stdlib.h>
@@ -17,4 +18,16 @@ extern "C" void runInNewThread(void(*callback)(void)) {
callback();
});
t.join();
}
extern "C" void runInForeignThread(void(*callback)(void)) {
std::thread t([callback]() {
// This thread is not attached to the Kotlin runtime.
auto future = std::async(std::launch::async, callback);
// The machinery of the direct interop doesn't filter out a Kotlin exception thrown by the callback.
// The get() call will re-throw this exception.
future.get();
});
t.join();
}
@@ -17,4 +17,5 @@ int32_t answer() {
return 42;
}
void runInNewThread(void(*callback)(void));
void runInNewThread(void(*callback)(void));
void runInForeignThread(void(*callback)(void));
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
import kotlin.native.concurrent.*
import kotlin.native.internal.Debugging
import kotlinx.cinterop.staticCFunction
import threadStates.*
fun main() {
val hook = { throwable: Throwable ->
print("${throwable::class.simpleName}. Runnable state: ${Debugging.isThreadStateRunnable}")
}
if (Platform.memoryModel != MemoryModel.EXPERIMENTAL) {
hook.freeze()
}
setUnhandledExceptionHook(hook)
runInNewThread(staticCFunction<Unit> { throw Error("Error") })
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
import kotlin.native.concurrent.*
import kotlin.native.internal.Debugging
import kotlinx.cinterop.staticCFunction
import threadStates.*
fun main() {
val hook = { throwable: Throwable ->
print("${throwable::class.simpleName}. Runnable state: ${Debugging.isThreadStateRunnable}")
}
if (Platform.memoryModel != MemoryModel.EXPERIMENTAL) {
hook.freeze()
}
setUnhandledExceptionHook(hook)
runInForeignThread(staticCFunction<Unit> { throw Error("Error") })
}