android关于pthread的使用过程

文章目录

简介

android开发经常需要使用pthread来编写代码实现相关的业务需求

代码流程

pthread使用

需要查询某个linux函数的方法使用,可以使用man + 函数名

cpp 复制代码
// $ man pthread_create
  #include <pthread.h>
  int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
cpp 复制代码
// $ man pthread_detach
   #include <pthread.h>
   int pthread_detach(pthread_t thread);

hello_test.cpp

cpp 复制代码
#include <utils/Log.h>
#include <pthread.h>
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "hello_test"

pthread_t thread_id;

void deal_data(){
    ALOGD("deal_data");
}

static void *start_thread_func (void *arg){
    ALOGD("start_thread_func");
    pthread_detach(thread_id);
    deal_data();
    return nullptr;
}

int main(int args,char** argv) {
    ALOGD("main");
    if(pthread_create(&thread_id,nullptr,start_thread_func,nullptr/**this**/) == 0){
       	 ALOGD("pthread_create success");
    }else{
       	 ALOGD("pthread_create failed");
    }
    sleep(5);
    ALOGD("main end");
    return 0;
}

Android.bp

bash 复制代码
cc_binary{
    name:"hello_test",
    srcs:[
        "hello_test.cpp",
    ],
    shared_libs:[
        "liblog",
        "libutils",
    ],

    cflags: [
            "-Wno-error",
            "-Wno-unused-parameter",
        ],
}

编译过程报错处理

cflags的配置

从编译报错可以看出是unused parameter 'xxx' [-Werror,-Wunused-parameter],刚开始以为直接配置报错的参数就好了,发现没有用,下次编译还是报错。

百度一波,说明如下:

解决-Werror,-Wunused类似问题万能公式 将"-Wunused-parameter"形式修改为"-Wno-unused-parameter"形式。其关键是将"-W"修改为:-Wno-,后边保持不变即可。

即可编译成功。

验证过程

adb push hello_test /system/bin

执行

bash 复制代码
/system/bin # ./hello_test

可以看到日志可以正常输出,打印如下所示

bash 复制代码
06-08 15:40:20.727  1978  1978 D hello_test: main
06-08 15:40:20.728  1978  1978 D hello_test: pthread_create success
06-08 15:40:20.728  1978  1979 D hello_test: start_thread_func
06-08 15:40:20.728  1978  1979 D hello_test: deal_data
06-08 15:40:25.728  1978  1978 D hello_test: main end
相关推荐
Mart!nHu15 分钟前
Android 10&15 Framework 允许设置系统时间早于编译时间
android
编程之路从0到11 小时前
ReactNative新架构之Android端TurboModule机制完全解析
android·react native·源码阅读
iloveAnd2 小时前
Android开发中痛点解决(二)兼容性:AndroidX和gradle版本的兼容性
android·兼容性·androidx
stevenzqzq2 小时前
DataStore基本使用教程
android
LawrenceMssss3 小时前
由于创建一个完整的App涉及到多个层面(如前端、后端、数据库等),并且每种语言通常有其特定的用途(如Java/Kotlin用于Android开发,Swift/Objective-C用于iOS开发,Py
android·java·ios
chen_mangoo4 小时前
HDMI简介
android·linux·驱动开发·单片机·嵌入式硬件
阿里-于怀4 小时前
AgentScope AutoContextMemory:告别 Agent 上下文焦虑
android·java·数据库·agentscope
Larry_Yanan5 小时前
Qt安卓开发(三)双摄像头内嵌布局
android·开发语言·c++·qt·ui
粲然忧生5 小时前
腾讯云终端性能监控SDK正式上线,为鸿蒙开发适配保驾护航
android·腾讯云·harmonyos
我命由我123455 小时前
Kotlin 开发 - Kotlin Lambda 表达式返回值
android·java·开发语言·java-ee·kotlin·android studio·android-studio