现在的位置: 首页 > 综合 > 正文

android ndk 线程使用与sleep

2013年12月07日 ⁄ 综合 ⁄ 共 830字 ⁄ 字号 评论关闭

#include <pthread.h>
#include <unistd.h> // sleep 的头文件
#include <android/log.h>

 

pthread_cond_t cond;
pthread_mutex_t mutex;
struct timeval now;
struct timespec outtime;

// 单位毫秒
void LTSleep(int nHm) {
 gettimeofday(&now, NULL);
 now.tv_usec += 1000*nHm;
 if (now.tv_usec > 1000000) {
  now.tv_sec += now.tv_usec / 1000000;
  now.tv_usec %= 1000000;
 }

 outtime.tv_sec = now.tv_sec;
 outtime.tv_nsec = now.tv_usec * 1000;

 pthread_cond_timedwait(&cond, &mutex, &outtime);
}

void* thread_run(void* arg) {
 fatherclass* thisa = (fatherclass*)arg;

 while (thisa->threadFlag) {
  ....
  //sleep(thisa->sleepTime);
  LTSleep(30);

 }

 __android_log_print(ANDROID_LOG_WARN, "thread_run", "exit");
 pthread_exit(0);
 return 0;
}

 

使用:

void fatherclass::start(){
 pthread_t pt;
 pthread_create(&pt, NULL, &thread_run, (void *)this);
}

 

这里写了一个sleep函数。因为sleep参数是秒,我想用毫秒。

另外:pthread_cond_timedwait 我只当计时器用了。其中前两个参数有很大价值。大家可以选择性学习一下。

 

抱歉!评论已关闭.