Posted by: slworkthings | March 21, 2011

Android NDK with PThread

After spending several hours debugging, I finally figure out how to solve the crash in my native code while calling pthread_exit(). The log showed “thread exiting, not yet detached (count=0)“.

Scenario:

I have an Android java code which will call my JNI (NDK) native code. In my native code, I create a pthread and in my pthread loop, I called AttachCurrentThread() to the JVM in the beginning of the loop.

When my java code finish some jobs, I need to stop the pthread and it crashed at the end of pthread loop.

Solution:

So, before I exit my pthread loop (before calling pthread_exit), I need to make sure I do call DetachCurrentThread from JVM.

Advertisement

Responses

  1. could you provide me the java and cpp/c source of the pthread issue you mentioned above

    • Hi bongo,
      here is a pseudo code for this:

      1. First, you create a pthread with pthread_create(&id, &attr, thread_func, this);
      2. Second, in your thread_func()

      void *thread_func(void *yourData)
      {
      jvm->AttachCurrentThread(...); //Important

      whileloop
      {
      do_your_heavy_thing_in_thread();
      and_maybe_call_your_java_method_from_c_here();
      }

      jvm->DetachCurrentThread(...); //Important
      }


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.