android源码c语言创建线程

212 阅读1分钟

- pthread

//Android.mk
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES := thread_posix.c

LOCAL_MODULE := linux_thread
LOCAL_SHARED_LIBRARIES := liblog

include $(BUILD_EXECUTABLE)
//thread_posix.c
#include "pthread.h"
#include "stdlib.h"
#include "stdio.h"
#include "utils/Log.h"

void *thread_posix_function(void *arg) {
    //do something
    return NULL;
}

int main(void) {
    pthread_t myThread;
    if (pthread_create(&myThread, NULL, thread_posix_function, NULL)) {//create and run
        printf("error creating thread");
        abort();
    }
    if (pthread_join(myThread, NULL)) {//it will block the main thread
        printf("error joining thread");
        abort();
    }
    printf("hello thread has run done.");
    exit(0);
}

- Thread

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_SRC_FILES := MyThread.cpp \
                   Main.cpp \

LOCAL_MODULE := android_thread

LOCAL_SHARED_LIBRARIES := liblog \
                          libcutils \
                          libutils \
                          libandroid_runtime \

LOCAL_PRELINK_MODULE := false

include $(BUILD_EXECUTABLE)
//MyThread.h
#include "utils/threads.h"

namespace android {
    class MyThread: public Thread {
        public:
            MyThread();
            virtual void onFirstRef();
            virtual status_t readyToRun();
            virtual bool threadLoop();
            virtual void requestExit();
        private:
            int hasRunCount = 0;
    };
}
//MyThread.cpp
#include "utils/Log.h"
#include "MyTherad.h"
#include "stdio.h"
#include "utils/CallStack.h"

namespace android {
    MyThread::MyThread() : Thread (false) {
        printf("MyThread");
    }
    bool MyThread::threadLoop() {
        printf("threadLoop, hasRunCount = %d\n", hasRunCount);
        hasRunCount++;
        if (hasRunCount == 10) {
            return false;
        }
        return true;
    }
    void MyThread::onFirstRef() {
        printf("onFirstRef\n");
    }

    int MyThread::readyToRun() {
        printf("readyToRun\n");
        return 0;
    }

    void MyThread::requestExit() {
        printf("requestExit\n");
    }
}
//Main.cpp
#include "utils/Log.h"
#include "utils/threads.h"
#include "MyTherad.h"
#include "stdio.h"

using namespace android;

int main() {
    sp<MyThread> thread = new MyThread;
    thread->run("MyThread", PRIORITY_URGENT_DISPLAY);
    while (1) {
        if (!thread->isRunning()) {
            printf("main thread->isRunning == false\n");
            break;
        }
        printf("main thread->isRunning == true\n");
    }
    printf("main end\n");
    return 0;
}