ndk开发之多线程同步与通信

在进行android的ndk开发时,耗时任务会用到native子线程。在pthread头文件中定义有创建子线程、互斥锁、条件变量等相关方法。线程同步是利用互斥锁(mutex)与条件(condition)变量的结合,经常出现于生产者与消费者模式场景中。

先定义相关变量:

#include <pthread.h>
//生产者线程
pthread_t thread_product;
//消费者线程
pthread_t thread_consume;
//互斥锁
pthread_mutex_t mutex;
//条件变量
pthread_cond_t cond;
//计数变量
int count;
//等待时长
timespec wait_time;
//是否处于运行状态
bool is_running;

生产者线程中,先用mutex来lock,执行完既定任务后,通过cond来通知唤醒,再unlock:

//生产者线程
void* product_func(void* arg){
    while(is_running) {
        //上锁
        pthread_mutex_lock(&mutex);
        for(count=0; count<10; ++count){
            LOGI("count=%d", count);
        }
        sleep(10);
        LOGI("product finish, notify consume thread...");
        //持有mutex引用的通知
        pthread_cond_signal(&cond);
        //广播通知
        //pthread_cond_broadcast(&cond);
        //解锁
        pthread_mutex_unlock(&mutex);
    }
}

如果需要广播通知,使用broadcast代替signal:

//广播通知
pthread_cond_broadcast(&cond);

消费者线程中,先用mutex来lock,用cond来等待通知唤醒。收到通知后,往下执行,最后unlock:

//消费者线程
void* consume_func(void* arg){
    while (is_running){
        //上锁
        pthread_mutex_lock(&mutex);
        //等待通知
        pthread_cond_wait(&cond, &mutex);
        //指定时间内等待通知,超时自动唤醒
        //wait_time.tv_sec = 10;
        //pthread_cond_timedwait(&cond, &mutex, &wait_time);
        LOGI("consume time, and count=%d", count);
        //解锁
        pthread_mutex_unlock(&mutex);
    }
}

如果需要在指定时间内等待,使用timewait代替wait:

//指定时间内等待通知,超时自动唤醒
wait_time.tv_sec = 10;
pthread_cond_timedwait(&cond, &mutex, &wait_time);

初始化互斥锁、条件变量,创建生产者、消费者线程:

JNIEXPORT void JNICALL
Java_com_frank_fix_MainActivity_start(){
    LOGI("start");
    is_running = true;
    //初始化互斥锁
    pthread_mutex_init(&mutex, NULL);
    //初始化条件变量
    pthread_cond_init(&cond, NULL);
    //创建生产者、消费者线程
    pthread_create(&thread_product, NULL, product_func, (void*)"product");
    pthread_create(&thread_consume, NULL, consume_func, (void*)"consume");
    //线程加入队列,运行起来
    pthread_join(thread_product, NULL);
    pthread_join(thread_consume, NULL);
}

任务执行完毕,释放互斥锁、条件变量,退出线程:

JNIEXPORT void JNICALL
Java_com_frank_fix_MainActivity_stop(){
    LOGI("stop");
    //释放互斥锁
    pthread_mutex_destroy(&mutex);
    //释放条件变量
    pthread_cond_destroy(&cond);
    is_running = false;
    //退出线程
    pthread_exit(0);
}
好了,ndk中多线程同步与通信介绍完毕。如果大家有问题或建议,欢迎交流。
发布了63 篇原创文章 · 获赞 179 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u011686167/article/details/79319351