手机版
你好,游客 登录 注册
背景:
阅读新闻

使用C++实现JNI接口需要注意的事项

[日期:2011-05-31] 来源:Linux社区  作者:feifei454498130 [字体:大 中 小]

也就是说如果定义了HAVE_PTHREADS宏,就有Mutex的相关方法实现,如果没有定义这个宏,Mutex的方法又是如何实现的,下面看看frameworks/base/libs/utils/Threads.cpp中的代码:

  1. #if defined(HAVE_PTHREADS)   
  2. // implemented as inlines in threads.h   
  3. #elif defined(HAVE_WIN32_THREADS)   
  4. Mutex::Mutex()   
  5. {   
  6.     HANDLE hMutex;   
  7.     assert(sizeof(hMutex) == sizeof(mState));   
  8.     hMutex = CreateMutex(NULL, FALSE, NULL);   
  9.     mState = (void*) hMutex;   
  10. }   
  11. Mutex::Mutex(const char* name)   
  12. {   
  13.     // XXX: name not used for now   
  14.     HANDLE hMutex;   
  15.     assert(sizeof(hMutex) == sizeof(mState));   
  16.     hMutex = CreateMutex(NULL, FALSE, NULL);   
  17.     mState = (void*) hMutex;   
  18. }   
  19. Mutex::Mutex(int type, const char* name)   
  20. {   
  21.     // XXX: type and name not used for now   
  22.     HANDLE hMutex;   
  23.     assert(sizeof(hMutex) == sizeof(mState));   
  24.     hMutex = CreateMutex(NULL, FALSE, NULL);   
  25.     mState = (void*) hMutex;   
  26. }   
  27. Mutex::~Mutex()   
  28. {   
  29.     CloseHandle((HANDLE) mState);   
  30. }   
  31. status_t Mutex::lock()   
  32. {   
  33.     DWORD dwWaitResult;   
  34.     dwWaitResult = WaitForSingleObject((HANDLE) mState, INFINITE);   
  35.     return dwWaitResult != WAIT_OBJECT_0 ? -1 : NO_ERROR;   
  36. }   
  37. void Mutex::unlock()   
  38. {   
  39.     if (!ReleaseMutex((HANDLE) mState))   
  40.         LOG(LOG_WARN, "thread", "WARNING: bad result from unlocking mutex\n");   
  41. }   
  42. status_t Mutex::tryLock()   
  43. {   
  44.     DWORD dwWaitResult;   
  45.     dwWaitResult = WaitForSingleObject((HANDLE) mState, 0);   
  46.     if (dwWaitResult != WAIT_OBJECT_0 && dwWaitResult != WAIT_TIMEOUT)   
  47.         LOG(LOG_WARN, "thread", "WARNING: bad result from try-locking mutex\n");   
  48.     return (dwWaitResult == WAIT_OBJECT_0) ? 0 : -1;   
  49. }   
  50. #else   
  51. #error "Somebody forgot to implement threads for this platform."   
  52. #endif  
也就是说,要么定义HAVE_PTHREADS宏,要么定义HAVE_WIN32_THREADS宏,否则,Mutex类的方法就没有实现代码。对于andorid来说,需要定义HAVE_PTHREADS宏。从上面的代码中还可以看出,Android的线程实现实际上还是使用了pthread库,只是在上面进行了一个封装。在Android.mk中增加下面一条语句,问题解决:

LOCAL_CXXFLAGS := -DHAVE_PTHREADS 

4. jni函数名带下划线,结果出错,将函数名的下划线去掉,解决问题。

linux
相关资讯       C++ 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款