美文网首页
[Kotlin] kotlin-native使用pthread

[Kotlin] kotlin-native使用pthread

作者: Cocoonshu | 来源:发表于2019-06-24 22:31 被阅读0次

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);

相关文章

  • [Kotlin] kotlin-native使用pthread

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

  • 如何用kotlin开发同时支持iOS和Android的库

    如何用kotlin开发同时支持iOS和Android的库 虽说kotlin-native可以支持链接到c,java...

  • kotlin-native01 项目搭建

    写在前面 发现国内介绍kotlin-native的文章很少,我很喜欢kotlin,打算写一系列教程。面向想要试试n...

  • 多线程之NSThread

    Pthread 使用pthread必须盗用头文件#import 可以使用[NSThread...

  • iOS 多线程的部分使用

    1.pthread 说明:pthread的基本使用(需要包含头文件) 使用pthread创建线程对象 pthrea...

  • iOS多线程总结

    pthread 使用方法 pthread是C语言的多线程库,使用pthread需要首先添加头文件 NSThread...

  • pthread使用

    引言: 针对上一篇文章的 线程的概念 的理论知识的实践 第一步: 第二步(创建线程): 附上demo地址方便测试...

  • pthread多线程(C语言) + Socket

    pthread多线程(C语言) + Socket pthread是使用使用C语言编写的多线程的API, 简称Pth...

  • pthread(了解)

    pthread(了解) phtread 使用步骤导入头文件 纯C语言,pthread(p:posix,posix是...

  • pthread,NSThread的使用

    iOS中多线程的实现方案: 一、pthread的基本使用 pthread的基本使用(需要包含头文件) 二、NSTh...

网友评论

      本文标题:[Kotlin] kotlin-native使用pthread

      本文链接:https://www.haomeiwen.com/subject/ykiaqctx.html