Android Framework中Thread類


Thread類是Android為線程操作而做的一個封裝。代碼在Thread.cpp中,其中還封裝了一些與線程同步相關的類。

Thread類

Thread類的構造函數中的有一個canCallJava
Thread.cpp

/system/core/libutils/Threads.cpp

線程創建流程

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// #define LOG_NDEBUG 0
#define LOG_TAG "libutils.threads"

#include <assert.h>
#include <errno.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#if !defined(_WIN32)
# include <pthread.h>
# include <sched.h>
# include <sys/resource.h>
#else
# include <windows.h>
# include <stdint.h>
# include <process.h>
# define HAVE_CREATETHREAD  // Cygwin, vs. HAVE__BEGINTHREADEX for MinGW
#endif

#if defined(__linux__)
#include <sys/prctl.h>
#endif

#include <utils/threads.h>
#include <utils/Log.h>

#include <cutils/sched_policy.h>

#ifdef HAVE_ANDROID_OS
# define __android_unused
#else
# define __android_unused __attribute__((__unused__))
#endif

/*
 * ===========================================================================
 *      Thread wrappers
 * ===========================================================================
 */

using namespace android;

// ----------------------------------------------------------------------------
#if !defined(_WIN32)
// ----------------------------------------------------------------------------

/*
 * Create and run a new thread.
 *
 * We create it "detached", so it cleans up after itself.
 */

typedef void* (*android_pthread_entry)(void*);

struct thread_data_t {
    thread_func_t   entryFunction;
    void*           userData;
    int             priority;
    char *          threadName;

    // we use this trampoline when we need to set the priority with
    // nice/setpriority, and name with prctl.
    static int trampoline(const thread_data_t* t) {
        thread_func_t f = t->entryFunction;
        void* u = t->userData;
        int prio = t->priority;
        char * name = t->threadName;
        delete t;
        setpriority(PRIO_PROCESS, 0, prio);
        if (prio >= ANDROID_PRIORITY_BACKGROUND) {
            set_sched_policy(0, SP_BACKGROUND);
        } else {
            set_sched_policy(0, SP_FOREGROUND);
        }

        if (name) {
            androidSetThreadName(name);
            free(name);
        }
        return f(u);
    }
};

void androidSetThreadName(const char* name) {
#if defined(__linux__)
    // Mac OS doesn't have this, and we build libutil for the host too
    int hasAt = 0;
    int hasDot = 0;
    const char *s = name;
    while (*s) {
        if (*s == '.') hasDot = 1;
        else if (*s == '@') hasAt = 1;
        s++;
    }
    int len = s - name;
    if (len < 15 || hasAt || !hasDot) {
        s = name;
    } else {
        s = name + len - 15;
    }
    prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);
#endif
}

int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
                               void *userData,
                               const char* threadName __android_unused,
                               int32_t threadPriority,
                               size_t threadStackSize,
                               android_thread_id_t *threadId)
{
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

#ifdef HAVE_ANDROID_OS  /* valgrind is rejecting RT-priority create reqs */
    if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
        // Now that the pthread_t has a method to find the associated
        // android_thread_id_t (pid) from pthread_t, it would be possible to avoid
        // this trampoline in some cases as the parent could set the properties
        // for the child.  However, there would be a race condition because the
        // child becomes ready immediately, and it doesn't work for the name.
        // prctl(PR_SET_NAME) only works for self; prctl(PR_SET_THREAD_NAME) was
        // proposed but not yet accepted.
        thread_data_t* t = new thread_data_t;
        t->priority = threadPriority;
        t->threadName = threadName ? strdup(threadName) : NULL;
        t->entryFunction = entryFunction;
        t->userData = userData;
        entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
        userData = t;
    }
#endif

    if (threadStackSize) {
        pthread_attr_setstacksize(&attr, threadStackSize);
    }

    errno = 0;
    pthread_t thread;
    int result = pthread_create(&thread, &attr,
                    (android_pthread_entry)entryFunction, userData);
    pthread_attr_destroy(&attr);
    if (result != 0) {
        ALOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"
             "(android threadPriority=%d)",
            entryFunction, result, errno, threadPriority);
        return 0;
    }

    // Note that *threadID is directly available to the parent only, as it is
    // assigned after the child starts.  Use memory barrier / lock if the child
    // or other threads also need access.
    if (threadId != NULL) {
        *threadId = (android_thread_id_t)thread; // XXX: this is not portable
    }
    return 1;
}

#ifdef HAVE_ANDROID_OS
static pthread_t android_thread_id_t_to_pthread(android_thread_id_t thread)
{
    return (pthread_t) thread;
}
#endif

android_thread_id_t androidGetThreadId()
{
    return (android_thread_id_t)pthread_self();
}

// ----------------------------------------------------------------------------
#else // !defined(_WIN32)
// ----------------------------------------------------------------------------

/*
 * Trampoline to make us __stdcall-compliant.
 *
 * We're expected to delete "vDetails" when we're done.
 */
struct threadDetails {
    int (*func)(void*);
    void* arg;
};
static __stdcall unsigned int threadIntermediary(void* vDetails)
{
    struct threadDetails* pDetails = (struct threadDetails*) vDetails;
    int result;

    result = (*(pDetails->func))(pDetails->arg);

    delete pDetails;

    ALOG(LOG_VERBOSE, "thread", "thread exiting\n");
    return (unsigned int) result;
}

/*
 * Create and run a new thread.
 */
static bool doCreateThread(android_thread_func_t fn, void* arg, android_thread_id_t *id)
{
    HANDLE hThread;
    struct threadDetails* pDetails = new threadDetails; // must be on heap
    unsigned int thrdaddr;

    pDetails->func = fn;
    pDetails->arg = arg;

#if defined(HAVE__BEGINTHREADEX)
    hThread = (HANDLE) _beginthreadex(NULL, 0, threadIntermediary, pDetails, 0,
                    &thrdaddr);
    if (hThread == 0)
#elif defined(HAVE_CREATETHREAD)
    hThread = CreateThread(NULL, 0,
                    (LPTHREAD_START_ROUTINE) threadIntermediary,
                    (void*) pDetails, 0, (DWORD*) &thrdaddr);
    if (hThread == NULL)
#endif
    {
        ALOG(LOG_WARN, "thread", "WARNING: thread create failed\n");
        return false;
    }

#if defined(HAVE_CREATETHREAD)
    /* close the management handle */
    CloseHandle(hThread);
#endif

    if (id != NULL) {
          *id = (android_thread_id_t)thrdaddr;
    }

    return true;
}

int androidCreateRawThreadEtc(android_thread_func_t fn,
                               void *userData,
                               const char* /*threadName*/,
                               int32_t /*threadPriority*/,
                               size_t /*threadStackSize*/,
                               android_thread_id_t *threadId)
{
    return doCreateThread(  fn, userData, threadId);
}

android_thread_id_t androidGetThreadId()
{
    return (android_thread_id_t)GetCurrentThreadId();
}

// ----------------------------------------------------------------------------
#endif // !defined(_WIN32)

// ----------------------------------------------------------------------------

int androidCreateThread(android_thread_func_t fn, void* arg)
{
    return createThreadEtc(fn, arg);
}

int androidCreateThreadGetID(android_thread_func_t fn, void *arg, android_thread_id_t *id)
{
    return createThreadEtc(fn, arg, "android:unnamed_thread",
                           PRIORITY_DEFAULT, 0, id);
}

static android_create_thread_fn gCreateThreadFn = androidCreateRawThreadEtc;

int androidCreateThreadEtc(android_thread_func_t entryFunction,
                            void *userData,
                            const char* threadName,
                            int32_t threadPriority,
                            size_t threadStackSize,
                            android_thread_id_t *threadId)
{
    return gCreateThreadFn(entryFunction, userData, threadName,
        threadPriority, threadStackSize, threadId);
}

void androidSetCreateThreadFunc(android_create_thread_fn func)
{
    gCreateThreadFn = func;
}

#ifdef HAVE_ANDROID_OS
int androidSetThreadPriority(pid_t tid, int pri)
{
    int rc = 0;

#if !defined(_WIN32)
    int lasterr = 0;

    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
        rc = set_sched_policy(tid, SP_BACKGROUND);
    } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
        rc = set_sched_policy(tid, SP_FOREGROUND);
    }

    if (rc) {
        lasterr = errno;
    }

    if (setpriority(PRIO_PROCESS, tid, pri) < 0) {
        rc = INVALID_OPERATION;
    } else {
        errno = lasterr;
    }
#endif

    return rc;
}

int androidGetThreadPriority(pid_t tid) {
#if !defined(_WIN32)
    return getpriority(PRIO_PROCESS, tid);
#else
    return ANDROID_PRIORITY_NORMAL;
#endif
}

#endif

namespace android {

/*
 * ===========================================================================
 *      Mutex class
 * ===========================================================================
 */

#if !defined(_WIN32)
// implemented as inlines in threads.h
#else

Mutex::Mutex()
{
    HANDLE hMutex;

    assert(sizeof(hMutex) == sizeof(mState));

    hMutex = CreateMutex(NULL, FALSE, NULL);
    mState = (void*) hMutex;
}

Mutex::Mutex(const char* name)
{
    // XXX: name not used for now
    HANDLE hMutex;

    assert(sizeof(hMutex) == sizeof(mState));

    hMutex = CreateMutex(NULL, FALSE, NULL);
    mState = (void*) hMutex;
}

Mutex::Mutex(int type, const char* name)
{
    // XXX: type and name not used for now
    HANDLE hMutex;

    assert(sizeof(hMutex) == sizeof(mState));

    hMutex = CreateMutex(NULL, FALSE, NULL);
    mState = (void*) hMutex;
}

Mutex::~Mutex()
{
    CloseHandle((HANDLE) mState);
}

status_t Mutex::lock()
{
    DWORD dwWaitResult;
    dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);
    return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;
}

void Mutex::unlock()
{
    if (!ReleaseMutex((HANDLE) mState))
        ALOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");
}

status_t Mutex::tryLock()
{
    DWORD dwWaitResult;

    dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);
    if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)
        ALOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");
    return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;
}

#endif // !defined(_WIN32)


/*
 * ===========================================================================
 *      Condition class
 * ===========================================================================
 */

#if !defined(_WIN32)
// implemented as inlines in threads.h
#else

/*
 * Windows doesn't have a condition variable solution.  It's possible
 * to create one, but it's easy to get it wrong.  For a discussion, and
 * the origin of this implementation, see:
 *
 *  http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
 *
 * The implementation shown on the page does NOT follow POSIX semantics.
 * As an optimization they require acquiring the external mutex before
 * calling signal() and broadcast(), whereas POSIX only requires grabbing
 * it before calling wait().  The implementation here has been un-optimized
 * to have the correct behavior.
 */
typedef struct WinCondition {
    // Number of waiting threads.
    int                 waitersCount;

    // Serialize access to waitersCount.
    CRITICAL_SECTION    waitersCountLock;

    // Semaphore used to queue up threads waiting for the condition to
    // become signaled.
    HANDLE              sema;

    // An auto-reset event used by the broadcast/signal thread to wait
    // for all the waiting thread(s) to wake up and be released from
    // the semaphore.
    HANDLE              waitersDone;

    // This mutex wouldn't be necessary if we required that the caller
    // lock the external mutex before calling signal() and broadcast().
    // I'm trying to mimic pthread semantics though.
    HANDLE              internalMutex;

    // Keeps track of whether we were broadcasting or signaling.  This
    // allows us to optimize the code if we're just signaling.
    bool                wasBroadcast;

    status_t wait(WinCondition* condState, HANDLE hMutex, nsecs_t* abstime)
    {
        // Increment the wait count, avoiding race conditions.
        EnterCriticalSection(&condState->waitersCountLock);
        condState->waitersCount++;
        //printf("+++ wait: incr waitersCount to %d (tid=%ld)\n",
        //    condState->waitersCount, getThreadId());
        LeaveCriticalSection(&condState->waitersCountLock);

        DWORD timeout = INFINITE;
        if (abstime) {
            nsecs_t reltime = *abstime - systemTime();
            if (reltime < 0)
                reltime = 0;
            timeout = reltime/1000000;
        }

        // Atomically release the external mutex and wait on the semaphore.
        DWORD res =
            SignalObjectAndWait(hMutex, condState->sema, timeout, FALSE);

        //printf("+++ wait: awake (tid=%ld)\n", getThreadId());

        // Reacquire lock to avoid race conditions.
        EnterCriticalSection(&condState->waitersCountLock);

        // No longer waiting.
        condState->waitersCount--;

        // Check to see if we're the last waiter after a broadcast.
        bool lastWaiter = (condState->wasBroadcast && condState->waitersCount == 0);

        //printf("+++ wait: lastWaiter=%d (wasBc=%d wc=%d)\n",
        //    lastWaiter, condState->wasBroadcast, condState->waitersCount);

        LeaveCriticalSection(&condState->waitersCountLock);

        // If we're the last waiter thread during this particular broadcast
        // then signal broadcast() that we're all awake.  It'll drop the
        // internal mutex.
        if (lastWaiter) {
            // Atomically signal the "waitersDone" event and wait until we
            // can acquire the internal mutex.  We want to do this in one step
            // because it ensures that everybody is in the mutex FIFO before
            // any thread has a chance to run.  Without it, another thread
            // could wake up, do work, and hop back in ahead of us.
            SignalObjectAndWait(condState->waitersDone, condState->internalMutex,
                INFINITE, FALSE);
        } else {
            // Grab the internal mutex.
            WaitForSingleObject(condState->internalMutex, INFINITE);
        }

        // Release the internal and grab the external.
        ReleaseMutex(condState->internalMutex);
        WaitForSingleObject(hMutex, INFINITE);

        return res == WAIT_OBJECT_0 ? NO_ERROR : -1;
    }
} WinCondition;

/*
 * Constructor.  Set up the WinCondition stuff.
 */
Condition::Condition()
{
    WinCondition* condState = new WinCondition;

    condState->waitersCount = 0;
    condState->wasBroadcast = false;
    // semaphore: no security, initial value of 0
    condState->sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL);
    InitializeCriticalSection(&condState->waitersCountLock);
    // auto-reset event, not signaled initially
    condState->waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL);
    // used so we don't have to lock external mutex on signal/broadcast
    condState->internalMutex = CreateMutex(NULL, FALSE, NULL);

    mState = condState;
}

/*
 * Destructor.  Free Windows resources as well as our allocated storage.
 */
Condition::~Condition()
{
    WinCondition* condState = (WinCondition*) mState;
    if (condState != NULL) {
        CloseHandle(condState->sema);
        CloseHandle(condState->waitersDone);
        delete condState;
    }
}


status_t Condition::wait(Mutex& mutex)
{
    WinCondition* condState = (WinCondition*) mState;
    HANDLE hMutex = (HANDLE) mutex.mState;

    return ((WinCondition*)mState)->wait(condState, hMutex, NULL);
}

status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime)
{
    WinCondition* condState = (WinCondition*) mState;
    HANDLE hMutex = (HANDLE) mutex.mState;
    nsecs_t absTime = systemTime()+reltime;

    return ((WinCondition*)mState)->wait(condState, hMutex, &absTime);
}

/*
 * Signal the condition variable, allowing one thread to continue.
 */
void Condition::signal()
{
    WinCondition* condState = (WinCondition*) mState;

    // Lock the internal mutex.  This ensures that we don't clash with
    // broadcast().
    WaitForSingleObject(condState->internalMutex, INFINITE);

    EnterCriticalSection(&condState->waitersCountLock);
    bool haveWaiters = (condState->waitersCount > 0);
    LeaveCriticalSection(&condState->waitersCountLock);

    // If no waiters, then this is a no-op.  Otherwise, knock the semaphore
    // down a notch.
    if (haveWaiters)
        ReleaseSemaphore(condState->sema, 1, 0);

    // Release internal mutex.
    ReleaseMutex(condState->internalMutex);
}

/*
 * Signal the condition variable, allowing all threads to continue.
 *
 * First we have to wake up all threads waiting on the semaphore, then
 * we wait until all of the threads have actually been woken before
 * releasing the internal mutex.  This ensures that all threads are woken.
 */
void Condition::broadcast()
{
    WinCondition* condState = (WinCondition*) mState;

    // Lock the internal mutex.  This keeps the guys we're waking up
    // from getting too far.
    WaitForSingleObject(condState->internalMutex, INFINITE);

    EnterCriticalSection(&condState->waitersCountLock);
    bool haveWaiters = false;

    if (condState->waitersCount > 0) {
        haveWaiters = true;
        condState->wasBroadcast = true;
    }

    if (haveWaiters) {
        // Wake up all the waiters.
        ReleaseSemaphore(condState->sema, condState->waitersCount, 0);

        LeaveCriticalSection(&condState->waitersCountLock);

        // Wait for all awakened threads to acquire the counting semaphore.
        // The last guy who was waiting sets this.
        WaitForSingleObject(condState->waitersDone, INFINITE);

        // Reset wasBroadcast.  (No crit section needed because nobody
        // else can wake up to poke at it.)
        condState->wasBroadcast = 0;
    } else {
        // nothing to do
        LeaveCriticalSection(&condState->waitersCountLock);
    }

    // Release internal mutex.
    ReleaseMutex(condState->internalMutex);
}

#endif // !defined(_WIN32)

// ----------------------------------------------------------------------------

/*
 * This is our thread object!
 */

Thread::Thread(bool canCallJava)
    :   mCanCallJava(canCallJava),
        mThread(thread_id_t(-1)),
        mLock("Thread::mLock"),
        mStatus(NO_ERROR),
        mExitPending(false), mRunning(false)
#ifdef HAVE_ANDROID_OS
        , mTid(-1)
#endif
{
}

Thread::~Thread()
{
}

status_t Thread::readyToRun()
{
    return NO_ERROR;
}

status_t Thread::run(const char* name, int32_t priority, size_t stack)
{
    Mutex::Autolock _l(mLock);

    if (mRunning) {
        // thread already started
        return INVALID_OPERATION;
    }

    // reset status and exitPending to their default value, so we can
    // try again after an error happened (either below, or in readyToRun())
    mStatus = NO_ERROR;
    mExitPending = false;
    mThread = thread_id_t(-1);

    // hold a strong reference on ourself
    mHoldSelf = this;

    mRunning = true;

    bool res;
    if (mCanCallJava) {
        res = createThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    } else {
        res = androidCreateRawThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    }

    if (res == false) {
        mStatus = UNKNOWN_ERROR;   // something happened!
        mRunning = false;
        mThread = thread_id_t(-1);
        mHoldSelf.clear();  // "this" may have gone away after this.

        return UNKNOWN_ERROR;
    }

    // Do not refer to mStatus here: The thread is already running (may, in fact
    // already have exited with a valid mStatus result). The NO_ERROR indication
    // here merely indicates successfully starting the thread and does not
    // imply successful termination/execution.
    return NO_ERROR;

    // Exiting scope of mLock is a memory barrier and allows new thread to run
}

int Thread::_threadLoop(void* user)
{
    Thread* const self = static_cast<Thread*>(user);

    sp<Thread> strong(self->mHoldSelf);
    wp<Thread> weak(strong);
    self->mHoldSelf.clear();

#ifdef HAVE_ANDROID_OS
    // this is very useful for debugging with gdb
    self->mTid = gettid();
#endif

    bool first = true;

    do {
        bool result;
        if (first) {
            first = false;
            self->mStatus = self->readyToRun();
            result = (self->mStatus == NO_ERROR);

            if (result && !self->exitPending()) {
                // Binder threads (and maybe others) rely on threadLoop
                // running at least once after a successful ::readyToRun()
                // (unless, of course, the thread has already been asked to exit
                // at that point).
                // This is because threads are essentially used like this:
                //   (new ThreadSubclass())->run();
                // The caller therefore does not retain a strong reference to
                // the thread and the thread would simply disappear after the
                // successful ::readyToRun() call instead of entering the
                // threadLoop at least once.
                result = self->threadLoop();
            }
        } else {
            result = self->threadLoop();
        }

        // establish a scope for mLock
        {
        Mutex::Autolock _l(self->mLock);
        if (result == false || self->mExitPending) {
            self->mExitPending = true;
            self->mRunning = false;
            // clear thread ID so that requestExitAndWait() does not exit if
            // called by a new thread using the same thread ID as this one.
            self->mThread = thread_id_t(-1);
            // note that interested observers blocked in requestExitAndWait are
            // awoken by broadcast, but blocked on mLock until break exits scope
            self->mThreadExitedCondition.broadcast();
            break;
        }
        }

        // Release our strong reference, to let a chance to the thread
        // to die a peaceful death.
        strong.clear();
        // And immediately, re-acquire a strong reference for the next loop
        strong = weak.promote();
    } while(strong != 0);

    return 0;
}

void Thread::requestExit()
{
    Mutex::Autolock _l(mLock);
    mExitPending = true;
}

status_t Thread::requestExitAndWait()
{
    Mutex::Autolock _l(mLock);
    if (mThread == getThreadId()) {
        ALOGW(
        "Thread (this=%p): don't call waitForExit() from this "
        "Thread object's thread. It's a guaranteed deadlock!",
        this);

        return WOULD_BLOCK;
    }

    mExitPending = true;

    while (mRunning == true) {
        mThreadExitedCondition.wait(mLock);
    }
    // This next line is probably not needed any more, but is being left for
    // historical reference. Note that each interested party will clear flag.
    mExitPending = false;

    return mStatus;
}

status_t Thread::join()
{
    Mutex::Autolock _l(mLock);
    if (mThread == getThreadId()) {
        ALOGW(
        "Thread (this=%p): don't call join() from this "
        "Thread object's thread. It's a guaranteed deadlock!",
        this);

        return WOULD_BLOCK;
    }

    while (mRunning == true) {
        mThreadExitedCondition.wait(mLock);
    }

    return mStatus;
}

bool Thread::isRunning() const {
    Mutex::Autolock _l(mLock);
    return mRunning;
}

#ifdef HAVE_ANDROID_OS
pid_t Thread::getTid() const
{
    // mTid is not defined until the child initializes it, and the caller may need it earlier
    Mutex::Autolock _l(mLock);
    pid_t tid;
    if (mRunning) {
        pthread_t pthread = android_thread_id_t_to_pthread(mThread);
        tid = pthread_gettid_np(pthread);
    } else {
        ALOGW("Thread (this=%p): getTid() is undefined before run()", this);
        tid = -1;
    }
    return tid;
}
#endif

bool Thread::exitPending() const
{
    Mutex::Autolock _l(mLock);
    return mExitPending;
}



};  // namespace android
View Code

 

http://androidxref.com/6.0.0_r1/xref/system/core/libutils/Threads.cpp

status_t Thread::run(const char* name, int32_tpriority, size_t stack)
{
   Mutex::Autolock_l(mLock);
    ....
   //如果mCanCallJava為真,則調用createThreadEtc函數,線程函數是_threadLoop。
 //_threadLoop是Thread.cpp中定義的一個函數。
   if(mCanCallJava) {
       res = createThreadEtc(_threadLoop,this, name, priority,
                                   stack,&mThread);
    } else{
       res = androidCreateRawThreadEtc(_threadLoop, this, name, priority,
                                   stack,&mThread);
    }

上面的mCanCallJava將線程創建函數的邏輯分為兩個分支,雖傳入的參數都有_threadLoop,但調用的函數卻不同。先直接看mCanCallJava為true的這個分支 
Thread.h::createThreadEtc()

inline bool createThreadEtc(thread_func_tentryFunction,
                            void *userData,
                            const char*threadName = "android:unnamed_thread",
                            int32_tthreadPriority = PRIORITY_DEFAULT,
                            size_tthreadStackSize = 0,
                            thread_id_t*threadId = 0)
{
    return androidCreateThreadEtc(entryFunction, userData, threadName,
                   threadPriority, threadStackSize,threadId) ? true : false;
}

它調用的是androidCreateThreadEtc函數

// gCreateThreadFn是函數指針,初始化時和mCanCallJava為false時使用的是同一個
//線程創建函數。
static android_create_thread_fn gCreateThreadFn= androidCreateRawThreadEtc;
int androidCreateThreadEtc(android_thread_func_tentryFunction,
                            void*userData,const char* threadName,
                            int32_tthreadPriority,size_t threadStackSize,
                            android_thread_id_t*threadId)
{
    return gCreateThreadFn(entryFunction, userData, threadName,
                               threadPriority,threadStackSize, threadId);
}

androidCreateThreadEtc方法最終會調用CreateThreadFn方法,初始化時和mCanCallJava為false時使用的是同一個
線程創建函數,所以我們要看一下到底什么地方會修改這個mCanCallJava的值。答案就在AndroidRuntime調用startReg的地方,就有可能修改這個函數指針
AndroidRuntime.cpp

/*static*/ int AndroidRuntime::startReg(JNIEnv*env)
{
   //這里會修改函數指針為javaCreateThreadEtc
  androidSetCreateThreadFunc((android_create_thread_fn)javaCreateThreadEtc);
  return 0;
}

所以,如果mCanCallJava為true,則將調用javaCreateThreadEtc。 
AndroidRuntime.cpp

int AndroidRuntime::javaCreateThreadEtc(
                               android_thread_func_tentryFunction,
                                void* userData,
                                const char*threadName,
                                int32_tthreadPriority,
                                size_t threadStackSize,
                               android_thread_id_t* threadId)
{
    void**args = (void**) malloc(3 * sizeof(void*));  
    intresult;
   args[0] = (void*) entryFunction;
   args[1] = userData;
   args[2] = (void*) strdup(threadName);
    //調用的還是androidCreateRawThreadEtc,但線程函數卻換成了javaThreadShell。
    result= androidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args,
                         threadName, threadPriority,threadStackSize, threadId);
    return result;
}

AndroidRuntime.cpp

http://androidxref.com/6.0.0_r1/xref/frameworks/base/core/jni/AndroidRuntime.cpp

int AndroidRuntime::javaThreadShell(void* args){
      ......
     intresult;
    //把這個線程attach到JNI環境中,這樣這個線程就可以調用JNI的函數了
    if(javaAttachThread(name, &env) != JNI_OK)
       return -1;
     //調用實際的線程函數干活
     result = (*(android_thread_func_t)start)(userData);
   //從JNI環境中detach出來。
   javaDetachThread();
   free(name);
    returnresult;
}

到這里,終於明白了mCanCallJava為true的目的:
1.在調用你的線程函數之前會attach到 JNI環境中,這樣,你的線程函數就可以無憂無慮地使用JNI函數了。
2.線程函數退出后,它會從JNI環境中detach,釋放一些資源。
進程退出前,dalvik虛擬機會檢查是否有attach了,但是最后未detach的線程如果有,則會直接abort,這顯然是不好的。

_threadLoop

還記得上面的代碼

  if(mCanCallJava) {
       res = createThreadEtc(_threadLoop,this, name, priority,
                                   stack,&mThread);
    } else{
       res = androidCreateRawThreadEtc(_threadLoop, this, name, priority,
                                   stack,&mThread);
    }

盡管根據mCanCallJava不同會調用不同的函數,但是都是傳入了_threadLoop,所以我們有必要分析這個方法。

int Thread::_threadLoop(void* user)
{
   Thread* const self = static_cast<Thread*>(user);
   sp<Thread> strong(self->mHoldSelf);
   wp<Thread> weak(strong);
   self->mHoldSelf.clear();

#if HAVE_ANDROID_OS
   self->mTid = gettid();
#endif

    boolfirst = true;

    do {
       bool result;
        if(first) {
           first = false;
          //self代表繼承Thread類的對象,第一次進來將調用readyToRun,看看是否准備好
          self->mStatus = self->readyToRun();
           result = (self->mStatus == NO_ERROR);

           if (result && !self->mExitPending) {
                result = self->threadLoop();
           }
        }else {
          /*
調用子類實現的threadLoop函數,注意這段代碼運行在一個do-while循環中。
             這表示即使我們的threadLoop返回了,線程也不一定會退出。
         */
           result = self->threadLoop();
        }
   /*
線程退出的條件:
    1)result 為false。這表明,如果子類在threadLoop中返回false,線程就可以
    退出。這屬於主動退出的情況,是threadLoop自己不想繼續干活了,所以返回false。千萬別寫錯threadLoop的返回值。
    2)mExitPending為true,這個變量可由Thread類的requestExit函數設置,這種
    情況屬於被動退出,因為由外界強制設置了退出條件。
   */
        if(result == false || self->mExitPending) {
           self->mExitPending = true;
           self->mLock.lock();
           self->mRunning = false;
           self->mThreadExitedCondition.broadcast();
           self->mLock.unlock();
           break;
        }
       strong.clear();
       strong = weak.promote();
    }while(strong != 0);

    return 0;
}

_threadLoop運行在一個循環中,它的返回值可以決定是否退出線程。

常用同步類

互斥類——Mutex
Mutex是互斥類,用於多線程訪問同一個資源的時候,保證一次只能有一個線程能訪問該資源。例如想象你在飛機上如廁,這時衛生間的信息牌上顯示“有人”,你必須等里邊的人出來后才可進去。這就是互斥的含義。

Thread.h::Mutex的聲明和實現

inline Mutex::Mutex(int type, const char* name){
    if(type == SHARED) {
      //type如果是SHARED,則表明這個Mutex支持跨進程的線程同步
      //在Audio系統和Surface系統中會經常見到這種用法
       pthread_mutexattr_t attr;
       pthread_mutexattr_init(&attr);
       pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
       pthread_mutex_init(&mMutex, &attr);
       pthread_mutexattr_destroy(&attr);
    } else {
       pthread_mutex_init(&mMutex, NULL);
    }
}
inline Mutex::~Mutex() {
   pthread_mutex_destroy(&mMutex);
}
inline status_t Mutex::lock() {
    return-pthread_mutex_lock(&mMutex);
}
inline void Mutex::unlock() {
   pthread_mutex_unlock(&mMutex);
}
inline status_t Mutex::tryLock() {
    return-pthread_mutex_trylock(&mMutex);
}

關於Mutex的使用,除了初始化外,最重要的是lock和unlock函數的使用,它們的用法如下:
要想獨占衛生間,必須先調用Mutex的lock函數。這樣,這個區域就被鎖住了。如果這塊區域之前已被別人鎖住,lock函數則會等待,直到可以進入這塊區域為止。系統保證一次只有一個線程能lock成功。
· 當你“方便”完畢,記得調用Mutex的unlock以釋放互斥區域。這樣,其他人的lock才可以成功返回。
· 另外,Mutex還提供了一個trylock函數,該函數只是嘗試去鎖住該區域,使用者需要根據trylock的返回值判斷是否成功鎖住了該區域。

AutoLock介紹
AutoLock類是定義在Mutex內部的一個類,Mutex的使用如下
· 顯示調用Mutex的lock。
· 在某個時候要記住調用該Mutex的unlock。以上這些操作都必須一一對應,否則會出現“死鎖”!充分利用了C++的構造和析構函數,可以達到不忘了釋放鎖的目的。
Thread.h Mutex::Autolock聲明和實現

  classAutolock {
   public:
        //構造的時候調用lock
       inline Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }
       inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }
        //析構的時候調用unlock
       inline ~Autolock() { mLock.unlock(); }
   private:
       Mutex& mLock;
    };

AutoLock的用法很簡單:
· 先定義一個Mutex,如 Mutex xlock;
· 在使用xlock的地方,定義一個AutoLock,如 AutoLock autoLock(xlock)。
由於C++對象的構造和析構函數都是自動被調用的,所以在AutoLock的生命周期內,xlock的lock和unlock也就自動被調用了,這樣就省去了重復書寫unlock的麻煩,而且lock和unlock的調用肯定是一一對應的,這樣就絕對不會出錯。

條件類——Condition
· 線程A做初始化工作,而其他線程比如線程B、C必須等到初始化工作完后才能工作,即線程B、C在等待一個條件,我們稱B、C為等待者。
· 當線程A完成初始化工作時,會觸發這個條件,那么等待者B、C就會被喚醒。觸發這個條件的A就是觸發者。
Thread.h::Condition的聲明和實現

class Condition {
public:
    enum {
       PRIVATE = 0,
       SHARED = 1
    };

   Condition();
   Condition(int type);//如果type是SHARED,表示支持跨進程的條件同步
   ~Condition();
    //線程B和C等待事件,wait這個名字是不是很形象呢?
   status_t wait(Mutex& mutex);
  //線程B和C的超時等待,B和C可以指定等待時間,當超過這個時間,條件卻還不滿足,則退出等待
   status_t waitRelative(Mutex& mutex, nsecs_t reltime);
    //觸發者A用來通知條件已經滿足,但是B和C只有一個會被喚醒
    voidsignal();
    //觸發者A用來通知條件已經滿足,所有等待者都會被喚醒
    voidbroadcast();

private:
#if defined(HAVE_PTHREADS)
   pthread_cond_t mCond;
#else
   void*   mState;
#endif
}

聲明很簡單,定義也很簡單

inline Condition::Condition() {
   pthread_cond_init(&mCond, NULL);
}
inline Condition::Condition(int type) {
    if(type == SHARED) {//設置跨進程的同步支持
       pthread_condattr_t attr;
        pthread_condattr_init(&attr);
       pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
       pthread_cond_init(&mCond, &attr);
       pthread_condattr_destroy(&attr);
    } else{
       pthread_cond_init(&mCond, NULL);
    }
}
inline Condition::~Condition() {
   pthread_cond_destroy(&mCond);
}
inline status_t Condition::wait(Mutex&mutex) {
    return-pthread_cond_wait(&mCond, &mutex.mMutex);
}
inline status_tCondition::waitRelative(Mutex& mutex, nsecs_t reltime) {
#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
    structtimespec ts;
   ts.tv_sec  = reltime/1000000000;
   ts.tv_nsec = reltime%1000000000;
    return-pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
    ...... //有些系統沒有實現POSIX的相關函數,所以不同系統需要調用不同的函數
#endif
}
inline void Condition::signal() {
   pthread_cond_signal(&mCond);
}
inline void Condition::broadcast() {
   pthread_cond_broadcast(&mCond);
}

可以看出,Condition的實現全是憑借調用了Raw API的pthread_cond_xxx函數。這里要重點說明的是,Condition類必須配合Mutex來使用。上面代碼中,不論是wait、waitRelative、signal還是broadcast的調用,都放在一個Mutex的lock和unlock范圍中,尤其是wait和waitRelative函數的調用,這是強制性的。

Condition類和Mutex類使用的例子,在Thread類的requestExitAndWait中就可以體現
Thread.cpp

status_t Thread::requestExitAndWait()
{
    ......
   requestExit();//設置退出變量mExitPending為true
    Mutex::Autolock_l(mLock);//使用Autolock,mLock被鎖住
    while(mRunning == true) {
    /*
     條件變量的等待,這里為什么要通過while循環來反復檢測mRunning?
     因為某些時候即使條件類沒有被觸發,wait也會返回。
   */
      mThreadExitedCondition.wait(mLock);
    }

   mExitPending = false;
   //退出前,局部變量Mutex::Autolock _l的析構會被調用,unlock也就會被自動調用。
    returnmStatus;
}

Thread.cpp

int Thread::_threadLoop(void* user)
{
    Thread* const self =static_cast<Thread*>(user);
   sp<Thread> strong(self->mHoldSelf);
   wp<Thread> weak(strong);
   self->mHoldSelf.clear();

    do {
          ......  
          result= self->threadLoop();//調用子類的threadLoop函數
           ......
         //如果mExitPending為true,則退出
        if(result == false || self->mExitPending) {
           self->mExitPending = true;
           //退出前觸發條件變量,喚醒等待者
           self->mLock.lock();//lock鎖住
           //mRunning的修改位於鎖的保護中。
            self->mRunning = false;
           self->mThreadExitedCondition.broadcast();
           self->mLock.unlock();//釋放鎖
           break;//退出循環,此后該線程函數會退出
        }
       ......
    }while(strong != 0);

    return0;
}

原子操作函數 
所謂原子操作,就是該操作絕不會在執行完畢前被任何其他任務或事件打斷,也就說,原子操作是最小的執行單位

static int g_flag = 0; //全局變量g_flag
static Mutex lock  ;//全局的鎖
//線程1執行thread1
void thread1()
{
  //g_flag遞減,每次操作前鎖住
  lock.lock();
   g_flag--;
 lock.unlock();
}
//線程2中執行thread2函數
void thread2()
{
  lock.lock();
  g_flag++; //線程2對g_flag進行遞增操作,每次操作前要取得鎖
lock.unlock();
}

為什么需要Mutex來幫忙呢?因為g_flags++或者g_flags—操作都不是原子操作。從匯編指令的角度看,C/C++中的一條語句對應了數條匯編指令。以g_flags++操作為例,它生成的匯編指令可能就是以下三條:
· 從內存中取數據到寄存器。
· 對寄存器中的數據進行遞增操作,結果還在寄存器中。
· 寄存器的結果寫回內存。
這三條匯編指令,如果按正常的順序連續執行,是沒有問題的,但在多線程時就不能保證了。例如,線程1在執行第一條指令后,線程2由於調度的原因,搶先在線程1之前連續執行完了三條指令。這樣,線程1繼續執行指令時,它所使用的值就不是線程2更新后的值,而是之前的舊值。再對這個值進行操作便沒有意義了。
在一般情況下,處理這種問題可以使用Mutex來加鎖保護,但Mutex的使用比它所要保護的內容還復雜,例如,鎖的使用將導致從用戶態轉入內核態,有較大的浪費。那么,有沒有簡便些的辦法讓這些加、減等操作不被中斷呢?
Android提供了相關的原子操作函數。這里,有必要介紹一下各個函數的作用。
Atomic.h
注意該文件位置在system/core/include/cutils目錄中

//原子賦值操作,結果是*addr=value
void android_atomic_write(int32_t value,volatile int32_t* addr);
//下面所有函數的返回值都是操作前的舊值
//原子加1和原子減1
int32_t android_atomic_inc(volatile int32_t*addr);
int32_t android_atomic_dec(volatile int32_t*addr);
//原子加法操作,value為被加數
int32_t android_atomic_add(int32_t value,volatile int32_t* addr);
//原子“與”和“或”操作
int32_t android_atomic_and(int32_t value,volatile int32_t* addr);
int32_t android_atomic_or(int32_t value,volatile int32_t* addr);
/*
條件交換的原子操作。只有在oldValue等於*addr時,才會把newValue賦值給*addr
這個函數的返回值須特別注意。返回值非零,表示沒有進行賦值操作。返回值為零,表示
進行了原子操作。
*/
int android_atomic_cmpxchg(int32_t oldvalue,int32_t newvalue,
                                volatile int32_t*addr);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM