/****************************************************************************** **函数名称: slot_creat **功 能: 创建内存池 **输入参数: ** num: 内存块数 ** size: 内存块大小 **输出参数: NONE **返 回: 内存池对象 **实现描述: **注意事项: **作 者: # Qifeng.zou # 2015.05.05 # ******************************************************************************/ slot_t *slot_creat(int num, size_t size) { int i; slot_t *slot; void *addr, *ptr; /* > 创建对象 */ slot = (slot_t *)calloc(1, sizeof(slot_t)); if (NULL == slot) { return NULL; } slot->max = num; slot->size = size; slot->ring = ring_creat(num); if (NULL == slot->ring) { free(slot); return NULL; } /* > 申请内存池空间 */ addr = (void *)calloc(num, size); if (NULL == addr) { ring_destroy(slot->ring); free(slot); return NULL; } /* > 插入管理队列 */ ptr = addr; for (i=0; i<num; ++i, ptr += size) { if (ring_push(slot->ring, ptr)) { ring_destroy(slot->ring); free(slot); free(addr); return NULL; } } return slot; }
int main() { //set buffer size as 5, first push 3 elements, and then pop 2 elements, then push 6 elements, at last pop 12 elements const int buffer_size = 5; int push_size_1 = 3; int pop_size_1 = 2; int push_size_2 = 6; int pop_size_2 = 12; void* data[buffer_size]; void* pop_data; struct ring* ring_buffer = ring_create( buffer_size ); int i; for( i = 0; i < push_size_1 ; i++){ data[i] = malloc(sizeof(int)); int err = ring_push(ring_buffer, &data[i]); if ( err == 0 ){ printf("push data %d = %d \n", i, &data[i]); } else{ printf("push %d failed \n ", i); } } for( i = 0; i < pop_size_1 ; i++){ pop_data = ring_pop(ring_buffer); if(pop_data == NULL){ printf("pop %d failed \n" , i); } else{ printf("pop data %d = %d\n", i, pop_data); } } for( i = 0; i < push_size_2 ; i++){ data[i] = malloc(sizeof(int)); int err = ring_push(ring_buffer, &data[i]); if ( err == 0 ){ printf("push data %d = %d \n", i, &data[i]); } else{ printf("push %d failed \n ", i); } } for( i = 0; i < pop_size_2 ; i++){ pop_data = ring_pop(ring_buffer); if(pop_data == NULL){ printf("pop %d failed \n" , i); } else{ printf("pop data %d = %d\n", i, pop_data); } } return 0; }
/* ------------------------------------------------------------------ * Push a character onto the tx buffer * ------------------------------------------------------------------ */ void uart_tx_push(uint8_t data) { ring_push(&tx, data); UART_CONTROL_STATUS_REG_B |= MASK(UART_DATA_REGISTER_EMPTY_INTERRUPT_ENABLE); }