Book Image

Android NDK: Beginner's Guide

By : Sylvain Ratabouil
Book Image

Android NDK: Beginner's Guide

By: Sylvain Ratabouil

Overview of this book

Table of Contents (18 chapters)
Android NDK Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – running and synchronizing a thread


Let's create a native thread using the POSIX PThread API and attach it to the VM:

  1. In Store.cpp, include unistd.h, which gives access to the sleep() function:

    #include "Store.h"
    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    ...

    Implement startWatcher(). This method is executed from the UI thread. To do so, first instantiate and initialize a StoreWatcher structure.

  2. Then, initialize and launch a native thread with the pthread POSIX API:

    StoreWatcher* startWatcher(JavaVM* pJavaVM, Store* pStore,
            jobject pLock) {
        StoreWatcher* watcher = new StoreWatcher();
        watcher->mJavaVM = pJavaVM;
        watcher->mStore = pStore;
        watcher->mLock = pLock;
        watcher->mRunning = true;
    ...

    Then, initialize and launch a native thread with the PThread POSIX API:

    • pthread_attr_init() initializes the necessary data structure

    • pthread_create() starts the thread

      ...
          pthread_attr_t lAttributes;
          if (pthread_attr_init...