附个人工作代码 条件变量深度运用、互斥锁+信号量

列一个我在工作上写的代码片段, 下面是消费者端的代码

static void input_status_report_thread(struct local_pthread_wrapper* thread, void* param) { struct input_manager *input = NULL; struct input_mode_lister *l = NULL; struct input_dev_param down_dev_param = {0}; struct input_dev_param up_app_param = {0}; struct input_manager_var *im_var = (struct input_manager_var *)param; down_dev_param.input_events = malloc(sizeof(struct input_dev_param) * MAX_INPUT_EVENT_COUNT); if(down_dev_param.input_events == NULL) log_e("malloc "); im_var->is_running = 1; pthread_mutex_init(&(down_dev_param.queue_lock), NULL); pthread_cond_init(&(down_dev_param.queue_ready), NULL); down_dev_param.fifo_it = alloc_fifo_iterator(down_dev_param.input_events, sizeof(struct input_dev_param), MAX_INPUT_EVENT_COUNT);while (im_var->is_running) { pthread_mutex_lock(&down_dev_param.queue_lock); list_for_each_entry(l, &unlock_mode_list, node) { input = l->dev_t; if (input->notify_status) { input->notify_status(&down_dev_param); } } if (fifo_empty(down_dev_param.fifo_it)) { log_i("等待下次事件\n"); //pthread_cond_wait中的mutex用于保护条件变量, // 调用这个函数等待条件的满足(或称呼为释放), 此时,mutex会被自动释放,以供其它线程(生产者)改变条件 //条件变量进入wait的时候,默认内部先对mutex解锁,以供生产者访问, //wait返回后(也就是生产者生产了新数据后, 此时轮到消费者去消费了)又会内部重新加锁,保证消费者独占该队列(共享资源) pthread_cond_wait(&down_dev_param.queue_ready, &down_dev_param.queue_lock); } while (!fifo_empty(down_dev_param.fifo_it)) { fifo_dequeue(down_dev_param.fifo_it, &up_app_param);//访问完上述队列,解锁。 交还资源权限给生产者. pthread_mutex_unlock(&down_dev_param.queue_lock); //then we need to deal the events... input_report_cb listener_by_CurSYSMode = NULL; list_for_each_entry(l, &im_var->list, node) { listener_by_CurSYSMode = (input_report_cb)l->dev_t; if (listener_by_CurSYSMode) { listener_by_CurSYSMode(&up_app_param); }else { log_w("listener_by_CurSYSMode NULL!\n"); } } memset(&up_app_param, 0x00, sizeof(struct input_dev_param) ); //下一步如果队列还有数据,又会出队(即访问队列)。 //因为有可能再次访问队列,所以这里先上锁!! pthread_mutex_lock(&down_dev_param.queue_lock); } /* end of while(!fifo_empty ...) */ pthread_mutex_unlock(&down_dev_param.queue_lock); } /* end of while(1) */ pthread_cond_destroy(&(down_dev_param.queue_ready)); pthread_mutex_destroy(&(down_dev_param.queue_lock)); log_e("input_status_report_thread\n"); pthread_exit(0); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpxgfw.html