[Kotlin] kotlin-native使用pthread

2019-06-24  本文已影响0人  Cocoonshu

kotlin-native号称可以直接使用posix接口跨操作系统编程。试试pthread的使用,体验一下kotlin-native的神奇。

示例

package sample

import kotlinx.cinterop.*
import platform.posix.*

/**
 * 对Int的扩展方法,用于检测并打印pthread函数的返回值(为int)
 * @param function 需要打印的方法名
 */
fun Int.detectResult(function: String?) {
    if (function != null)
        println("$function result is $this")
}

fun main() {
    memScoped { // 在这个代码域中开辟的内存,在代码域结束时都会自动回收
        val thread = alloc<pthread_tVar>() // 申请一个pthread_tVar句柄
        pthread_create(thread.ptr, null, staticCFunction<COpaquePointer?, COpaquePointer?> {
                println("run test")
                sleep(3U) // 耗时操作3s

                // TODO

        it }, null).detectResult("pthread_create")

        pthread_join(thread.value, null).detectResult("pthread_join") // 等待异步线程执行完毕
        println("run finished")
    }
}

剖析

函数原型

// Kotlin 函数原型
public fun pthread_create( thread: CValuesRef<pthread_tVar>?, 
                           attr: CValuesRef<pthread_attr_t>?, 
                           func: CPointer<CFunction<(COpaquePointer?) -> COpaquePointer?>>?, 
                           arg: CValuesRef<*>?)
                           : kotlin.Int

// C 函数原型
int pthread_create( pthread_t* thread,
                    const pthread_attr_t* attr,
                    void* (*start_routine)(void* ),
                    void* arg);
// Kotlin 函数原型
public fun pthread_join( thread: pthread_t,
                         res: CValuesRef<COpaquePointerVar>?)
                         : kotlin.Int
// C 函数原型
int pthread_join( pthread_t thread, 
                  void **retval);
上一篇 下一篇

猜你喜欢

热点阅读