Android NDK pthreads详细使用-程序员宅基地

技术标签: pthread  线程  NDK  JNI和NDK  Android  

这个pthread.h文件可以在NDK环境里创建子线程,并对线程能够做出互斥所、等待、销毁等控制。

写这个博客的原因是我要写如何使用FFmpeg播放视频,因为同时需要播放音频和视频所以需要开启线程,并设置生产者和消费者的关系。

好了直接上整体

1.开启和销毁线程


pthread_create函数能够创建线程,第一个参数是线程的引用,第二个是线程的属性,一般为NULL,第三个为线程运行的函数,第四个是给线程运行函数的参数

pthread_create又是开启线程,只要运行了这个函数线程就会运行起来,也就是运行第三个参数所代表的函数

    pthread_t pthreads;
    pthread_create(&pthreads, NULL, threadFunc, (void *) "zzw");
等待线程完成和返回参数,这个如果开启线程只有一个可以不写,但是如果有多个线程这个就必须要写,不写的话只会运行第一个线程
    int retvalue;
    pthread_join(pthreads,(void**)&retvalue);
    if(retvalue!=0){
        __android_log_print(ANDROID_LOG_ERROR,"hello","thread error occurred");
    }

我们再来看看线程运行函数,这个他可以获取参数,并且能能够提前结束线程

void * threadFunc(void *arg){

    char* str=(char*)arg;

    for(int i=0;i<3;i++){
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d arg = %s",i,str);
        //线程自杀,需要返回参数
        //pthread_exit((void*)2);
        //线程他杀
        //pthread_cancel()
    }
    return (void *) 0;

}

完整例子代码

#include <jni.h>
#include <string>
#include <android/log.h>
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"LC XXX",FORMAT,##__VA_ARGS__);

extern "C"
JNIEXPORT jstring
JNICALL
Java_com_example_zth_ndkthread_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}


void * threadFunc(void *arg){

    char* str=(char*)arg;

    for(int i=0;i<3;i++){
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d arg = %s",i,str);
        //线程自杀,需要返回参数
        //pthread_exit((void*)2);
        //线程他杀
        //pthread_cancel()
    }
    return (void *) 0;

}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_zth_ndkthread_MainActivity_startNativeThread(JNIEnv* env, jobject thiz,jint count) {


    pthread_t pthreads;
    pthread_create(&pthreads, NULL, threadFunc, (void *) "zzw");


    int retvalue;
    pthread_join(pthreads,(void**)&retvalue);
    if(retvalue!=0){
        __android_log_print(ANDROID_LOG_ERROR,"hello","thread error occurred");
    }


}

2.互斥锁


互斥锁指的是它能够锁住一段代码,使得这段代码在解锁之前不能再被执行一次,

初始化

    pthread_mutex_t pthread_mutex;
    if(pthread_mutex_init(&pthread_mutex,NULL)!=0)
        return;

开启线程时把互斥锁传给线程运行函数

    for(int i=0;i<count;i++){
        pthread_create(&pthreads[i],NULL,threadFunc,&pthread_mutex);
    }

我们再来看看线程运行函数
取出互斥锁并上锁

    pthread_mutex_t* pthread_mutex=(pthread_mutex_t*)arg;
    pthread_mutex_lock(pthread_mutex);

然后一段代码

    for(int i=0;i<3;i++){
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",i);
    }
    __android_log_print(ANDROID_LOG_VERBOSE,"hello","————————————");

解锁

pthread_mutex_unlock(pthread_mutex);

最后销毁互斥锁

    pthread_mutex_destroy(&pthread_mutex);

运行效果如下

03-02 14:25:58.346 10022-10077/com.example.zth.ndkthread V/hello: i = 0
03-02 14:25:58.346 10022-10077/com.example.zth.ndkthread V/hello: i = 1
03-02 14:25:58.346 10022-10077/com.example.zth.ndkthread V/hello: i = 2
03-02 14:25:58.346 10022-10077/com.example.zth.ndkthread V/hello: ------------------------
03-02 14:25:58.346 10022-10078/com.example.zth.ndkthread V/hello: i = 0
03-02 14:25:58.346 10022-10078/com.example.zth.ndkthread V/hello: i = 1
03-02 14:25:58.346 10022-10078/com.example.zth.ndkthread V/hello: i = 2
03-02 14:25:58.346 10022-10078/com.example.zth.ndkthread V/hello: ------------------------
03-02 14:25:58.347 10022-10079/com.example.zth.ndkthread V/hello: i = 0
03-02 14:25:58.347 10022-10079/com.example.zth.ndkthread V/hello: i = 1
03-02 14:25:58.347 10022-10079/com.example.zth.ndkthread V/hello: i = 2
03-02 14:25:58.347 10022-10079/com.example.zth.ndkthread V/hello: ————————————

如果我们没有加锁呢

    pthread_mutex_t* pthread_mutex=(pthread_mutex_t*)arg;
   // pthread_mutex_lock(pthread_mutex);
    for(int i=0;i<3;i++){
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",i);
    }
    __android_log_print(ANDROID_LOG_VERBOSE,"hello","------------------------");
   // pthread_mutex_unlock(pthread_mutex);

结果如下

03-02 14:36:50.035 13815-13993/com.example.zth.ndkthread V/hello: i = 0
03-02 14:36:50.035 13815-13993/com.example.zth.ndkthread V/hello: i = 1
03-02 14:36:50.035 13815-13993/com.example.zth.ndkthread V/hello: i = 2
03-02 14:36:50.035 13815-13993/com.example.zth.ndkthread V/hello: ------------------------
03-02 14:36:50.035 13815-13994/com.example.zth.ndkthread V/hello: i = 0
03-02 14:36:50.035 13815-13994/com.example.zth.ndkthread V/hello: i = 1
03-02 14:36:50.035 13815-13994/com.example.zth.ndkthread V/hello: i = 2
03-02 14:36:50.035 13815-13995/com.example.zth.ndkthread V/hello: i = 0
03-02 14:36:50.035 13815-13994/com.example.zth.ndkthread V/hello: ------------------------
03-02 14:36:50.035 13815-13995/com.example.zth.ndkthread V/hello: i = 1
03-02 14:36:50.035 13815-13995/com.example.zth.ndkthread V/hello: i = 2
03-02 14:36:50.035 13815-13995/com.example.zth.ndkthread V/hello: ------------------------

所以互斥锁是先让一个线程做完,然后另外一个线程做。

例子代码:

#include <jni.h>
#include <string>
#include <android/log.h>
#include "pthread.h"
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"LC XXX",FORMAT,##__VA_ARGS__);



extern "C"
JNIEXPORT jstring
JNICALL
Java_com_example_zth_ndkthread_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}


void * threadFunc(void *arg){

    pthread_mutex_t* pthread_mutex=(pthread_mutex_t*)arg;
    pthread_mutex_lock(pthread_mutex);
    for(int i=0;i<3;i++){
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",i);
    }
    __android_log_print(ANDROID_LOG_VERBOSE,"hello","------------------------");
    pthread_mutex_unlock(pthread_mutex);
    return (void *) 0;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_zth_ndkthread_MainActivity_startNativeThread(JNIEnv* env, jobject thiz,jint count) {

    pthread_mutex_t pthread_mutex;
    if(pthread_mutex_init(&pthread_mutex,NULL)!=0)
        return;

    pthread_t pthreads[count];
    for(int i=0;i<count;i++){
        pthread_create(&pthreads[i],NULL,threadFunc,&pthread_mutex);
    }

    for(int i=0;i<count;i++){
        int retvalue=0;
        pthread_join(pthreads[i],(void**)&retvalue);
        if(retvalue!=0){
            __android_log_print(ANDROID_LOG_ERROR,"hello","thread error occurred");
        }
    }

    pthread_mutex_destroy(&pthread_mutex);

}

3.条件变量


视频解码的绘制使用的就是生产者—消费者的模式。比如说我们生产者生成的产品,放到一个队列里面,当生产者生产出产品的时候就会发送信号通知消费者去消费

这个条件变量能够唤醒线程运行

初始化

pthread_cond_init(&c,NULL);

开启生成者线程和消费者线程

    pthread_create(&thread_producer, NULL, produce, (void *) "producer");
    pthread_create(&thread_comsumer, NULL, comsume, (void *) "comsumer");

循环生产产品,然后提醒消费者

    for(;;){
        pthread_mutex_lock(&m);
        productNum++;
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",productNum);
        pthread_cond_signal(&c);
        pthread_mutex_unlock(&m);

    }

消费者线程如果发现没有产品就等待条件变量提醒,,如果有产品就消费掉

        pthread_mutex_lock(&m);
        while(productNum == 0){
            pthread_cond_wait(&c,&m);

        }
        productNum--;
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",productNum);
        pthread_mutex_unlock(&m);

注意生成者与消费者线程运行的全过程都在互斥锁下,都是按顺序一一执行的,这样对于全局变量productNum的计算就不会错误,并且通过一个线程执行pthread_cond_signal来触发另一个线程执行

例子代码

#include <jni.h>
#include <string>
#include <android/log.h>
#include "pthread.h"
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"LC XXX",FORMAT,##__VA_ARGS__);



extern "C"
JNIEXPORT jstring
JNICALL
Java_com_example_zth_ndkthread_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

int productNum = 0;
pthread_mutex_t m;
pthread_cond_t c;

void *produce(void* arg){
    char* no = (char*)arg;
    for(;;){
        pthread_mutex_lock(&m);
        productNum++;
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",productNum);
        pthread_cond_signal(&c);
        pthread_mutex_unlock(&m);

    }
}

void *comsume(void* arg){
    char* no = (char*)arg;
    for(;;){
        pthread_mutex_lock(&m);
        while(productNum == 0){
            pthread_cond_wait(&c,&m);

        }
        productNum--;
        __android_log_print(ANDROID_LOG_VERBOSE,"hello","i = %d",productNum);
        pthread_mutex_unlock(&m);



    }
}


extern "C"
JNIEXPORT void JNICALL
Java_com_example_zth_ndkthread_MainActivity_startNativeThread(JNIEnv* env, jobject thiz,jint count) {

    pthread_mutex_init(&m,NULL);
    pthread_cond_init(&c,NULL);

    pthread_t thread_producer;
    pthread_t thread_comsumer;

    pthread_create(&thread_producer, NULL, produce, (void *) "producer");
    pthread_create(&thread_comsumer, NULL, comsume, (void *) "comsumer");

    pthread_join(thread_producer,NULL);
    pthread_join(thread_comsumer,NULL);

    pthread_mutex_destroy(&m);
    pthread_cond_destroy(&c);


}


参考文章

https://www.jianshu.com/p/453d12c16885

http://blog.csdn.net/lxmhuendan/article/details/11967593

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/z979451341/article/details/79423618

智能推荐

在Ubuntu为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口 (学习老罗的)_hal还能编译出java?-程序员宅基地

文章浏览阅读4k次。主要是在~/Android_4.2.2_SourceCode/frameworks/base/services/jni个夹子里面操作的。根据老罗的方法我也是实现成功了。但是和上一篇文章一样,同样需要将LOGI改为ALOGI,LOGE改为ALOGE。他也写了很多知识方面的内容,但是目前还只是实现了部分,待后面JAVA方面调用的例程写好了,我串起来总结一下。。。_hal还能编译出java?

Identify3D部署金雅拓解决方案以确保对用户IP和制造数据的保护_identify3d做什么用的-程序员宅基地

文章浏览阅读307次。这家数字制造软件提供商利用SafeNet Data Protection on Demand云端HSM服务来提升其数据安全性阿姆斯特丹--(美国商业资讯)--全球数字安全领域的领导者金雅拓(Gemalto)今天宣布,数字制造供应链的最先进安全解决方案提供商Identify3D已部署金雅拓的SafeNet Data Protection On Demand,以确保其客户知识产权的安全性和云端数字..._identify3d做什么用的

基于VMD-SSA-LSTM的多维时序光伏功率预测_知乎 vmd-ssa-lstm的多维时序光伏功率预测-程序员宅基地

文章浏览阅读1.9k次,点赞3次,收藏19次。之前分享了预测的程序,该程序预测效果比较好,并且结构比较清晰,但是仍然有同学咨询混合算法的预测,本次分享基于VMD-SSA-LSTM的多维时序光伏功率预测,本程序参考文章《基于VMD-SSA-LSSVM的短期风电预测》和《基于改进鲸鱼优化算法的微网系统能量优化管理》,采用不同方法混合嫁接的方式实现了光伏功率预测,对于预测而言,包括训练和测试,因此,该方法仍然可以用于风电、负荷等方面的预测。_知乎 vmd-ssa-lstm的多维时序光伏功率预测

分享一个从IEEE Xplore上批量下载会议论文的方法_ieee xplore 脚本-程序员宅基地

文章浏览阅读1.8w次,点赞5次,收藏11次。博客地址标签(空格分隔): IEEE Xplore, bash 测试环境:Ubuntu 15.04, 中山大学首先,从下载一篇论文开始,在IEEE Xplore上任意下载一篇论文,获取下载链接, 如:http://ieeexplore.ieee.org/ielx7/6875427/6877223/06877226.pdf?tp=&arnumber=6877226&isnumber=687722_ieee xplore 脚本

chrome代理插件下载安装_谷歌proxy插件下载-程序员宅基地

文章浏览阅读2.2k次。https://github.com/FelisCatus/SwitchyOmega/releases下载直接将下载的crx文件拖入开发者模式的扩展程序中安装chrome://extensions/若将SwitchyOmega_Chromium.crx拖到chrome里无法安装,可把此文件后缀改为.zip,拖到chrome里即可..._谷歌proxy插件下载

图像处理重点-程序员宅基地

文章浏览阅读243次。第一章 数字图像处理概论* 图像 是对客观存在对象的一种相似性的、生动性的描述或写真。* 模拟图像空间坐标和明暗程度都是连续变化的、计算机无法直接处理的图像* 数字图像空间坐标和灰度均不连续的、 用离散的数字 (一般整数)表示的图像 (计算机能处理)。是图像的数字表示,像素是其最小的单位。* 数字图像处理 (Digital Image Processing )利用计算机对数字图像进行 (..._2. 在实际的图像处理应用中,最主要的图像来源于电磁辐射成像,常见的电磁辐射

随便推点

linux执行脚本中方法,Linux中执行shell脚本命令的4种方法总结-程序员宅基地

文章浏览阅读6.3k次,点赞2次,收藏11次。bash shell 脚本的方法有多种,现在作个小结。假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限。方法一:切换到shell脚本所在的目录(此时,称为工作目录)执行shell脚本:复制代码 代码如下:cd /data/shell./hello.sh./的意思是说在当前的工作目录下执行hello.sh。如果不加上./,bash可能会响..._linux 怎么调用shell脚本中的方法

Dubbo服务调用过程?_dubbo status = 20, event = false, error = null,-程序员宅基地

文章浏览阅读685次。简单的想想大致流程在分析Dubbo的服务调用过程前我们先来思考一下如果让我们自己实现的话一次调用过程需要经历哪些步骤?首先我们已经知晓了远程服务的地址,然后我们要做的就是把我们要调用的方法具体信息告知远程服务,让远程服务解析这些信息。然后根据这些信息找到对应的实现类,然后进行调用,调用完了之后再原路返回,然后客户端解析响应再返回即可。调用具体的信息那客户端告知服务端的具体信息应该包含哪些呢?首先客户端肯定要告知要调用是服务端的哪个接口,当然还需要方法名、方法的参数类型、方法的参._dubbo status = 20, event = false, error = null,

ATR指标详细介绍-程序员宅基地

文章浏览阅读1.1w次。为想要了解外汇技术指标或者怎样分析做外汇以及如何使用市场ATR指标,以及ATR指标详细的计算方法、应用分析、使用方法、以及对外汇新手普及一些ATR知识。希望被采纳。工具/原料笔记本MT4平台方法/步骤 ATR指标详细介绍 ATR又称 Average _atr指标

iOS逆向学习笔记之--砸壳和导出应用头文件_dump.py -l-程序员宅基地

文章浏览阅读1.6k次。iOS逆向学习笔记之–砸壳和导出应用头文件dumpdecrypted砸壳工具的使用1、下载源代码git clone https://github.com/stefanesser/dumpdecrypted.git 2、进入dumpdecrypted文件夹目录。使用make命令生成dumpdecrypted.dylib文件 3、ssh登录越狱手机,关闭所有应用,启动需要砸壳的目标应用..._dump.py -l

python脚本运行gprMax3.0批量仿真GPR数据_gprmax 输出图像为txt-程序员宅基地

文章浏览阅读9.8k次,点赞11次,收藏98次。python脚本运行gprMax3.0批量仿真GPR B-scan图像1.引言2.Python脚本3.可能出现的报错4.数据展示1.引言探地雷达(GPR)结合深度学习通常需要大量的训练数据集,对于GPR仿真数据集的获取,我们一般通过gprMax生成,而gprMax3.0仿真数据时需要通过cmd命令提示符窗口人工一条一条地输入指令(通过cmd命令生成GPR B-scan图像:可以参考我的上一篇博客.),对于批量生成GPR数据非常不方便。因此,有必要写一些Python脚本,实现自动化批量生成GPR数据集。_gprmax 输出图像为txt

机器学习_factor_regression_data/factor_returns.csv-程序员宅基地

文章浏览阅读1.2k次。机器学习算法课程定位、目标定位课程以算法、案例为驱动的学习,伴随浅显易懂的数学知识作为人工智能领域(数据挖掘/机器学习方向)的提升课程,掌握更深更有效的解决问题技能目标应用Scikit-learn实现数据集的特征工程掌握机器学习常见算法原理应用Scikit-learn实现机器学习算法的应用,结合场景解决实际问题机器学习概述了解机器学习定义以及应用场景什么是机器学习1、 背景介..._factor_regression_data/factor_returns.csv

推荐文章

热门文章

相关标签