0

我尝试将 pigpio 库与 Kotlin/Native 一起使用。开始之前,我关注了这个演讲: Bridge The Physical World: Kotlin Native on Raspberry Pi

sigHandler: Unhandled signal 11, terminating当我尝试将从回调中获得的值分配给lastChange = tick第 54 行的全局变量时,就会发生这种情况

我的测试的整个代码如下所示:

package ch.lichtwellenreiter.omrr

import kotlinx.cinterop.staticCFunction
import pigpio.*

const val GPIO_BUTTON = 6
var lastChange: UInt = 0u

fun main() {
    initGPIO()
    println()

    setupButton()
    println()

    while (true) {}
}

private fun initGPIO() {
    println("Init GPIO")
    if (gpioInitialise() < 0) {
        println("GPIO Error initialising")
        return
    }
}

private fun setupButton() {
    println("Setup pin")
    val buttonPort = GPIO_BUTTON.toUInt()
    initPortWithMode(buttonPort, PI_INPUT)

    println("Register callback for pin")
    gpioSetAlertFunc(buttonPort, flankChangeDetected)
}

private fun initPortWithMode(port: UInt, mode: Int) {
    if (gpioSetMode(port, mode.toUInt()) < 0) {
        println("Could not set mode for GPIO$port")
        return
    }
}

val flankChangeDetected = staticCFunction<Int, Int, UInt, Unit> { gpio, level, tick ->

    println("Callback called")
    val ticker: UInt = tick
    val pin: Int = gpio
    val lvl: Int = level

    println("Calculate time")
    val time = ticker - lastChange

    println("Set lastChange")
    lastChange = tick

    println("Is DCC signal?")
    if ((time > 55u && time < 61u) || (time > 113u && time < 119u)) println(time)

    println()
}

我怎样才能防止这个错误?

4

2 回答 2

2

经过一番尝试,我找到了解决方案,但不知道这是否是最好的方法。

作为 AtomicInt 的全局变量不起作用,但它可以这样工作:

@SharedImmutable
val sharedData = SharedData()

class SharedData {
    var lastChange = AtomicInt(0)
}

这样我可以通过val lastChange = sharedData.lastChange.value和访问价值sharedData.lastChange.compareAndSet(lastChange, tick.toInt())

于 2020-10-01T09:05:34.590 回答
0

I would guess the problem is related to Kotlin/Native immutability rules. This issue I found convinced me to think that the callback is being called not on the main thread. If that's true, the error is caused by violating mutable XOR shared K/N's rule. Cannot write a snippet at the moment, but I think you can either try using AtomicInt or, if it fits the need here, @ThreadLocal annotation.

于 2020-09-29T08:07:18.843 回答