Explore a fixed-length queue operation (C language version)

Source: Internet
Author: User
Tags usleep

Explore a fixed-length queue operation (C language version)

I. Source: Nanjing beacon communication interview

Problem 2:

There is a fixed-length queue with a length of 2 to the N power. This queue can be accessed by multiple threads, but it must ensure the thread-level security, that is, the length of the queue remains unchanged at any time.

3. Author Analysis

1. Storage Structure of the queue-chain and sequential.

2. the length is 2 to the power of Npower-it is convenient to move the head and tail pointer of the team. If the queue length is size, rear = (rear + 1) & (size-1 ), & operations are more efficient than arithmetic modulo operations. For this reason, I use sequential queues.

3. How to Ensure line-level security

I believe that this system must have multiple readers and writers at the same time. The reader reads the element from the head of the team, and the writer constantly inserts the element into the end of the team, between the reader and the reader, and between the reader and the writer, the writer and the writer must access each other. Therefore, the mutex lock must be used to ensure that the length of the queue remains unchanged at any time. Therefore, the author defines a global variable balance.

Reader get

Lock

Is the balance detected 1? If the value is 1, it indicates that an element has been added at the end of the team, then read the team header and set balance = 0

Unlock

Writer put

Lock

Is the balance detected 0? If the value is 0, it indicates that the queue is balanced and no element is inserted. Then, insert the element in the queue and set balance = 1.

Unlock

This ensures that the read and writer are mutually exclusive at the same time.

4. Code Organization


5. Code details

1. queue. h

/*************************************************************************    > File Name: queue.h    > Author: wangzhicheng    > Mail: 2363702560@qq.com     > Created Time: Fri 14 Nov 2014 11:23:55 AM WST ************************************************************************/#ifndef _QUEUE_H_#define _QUEUE_H_#include 
 
  #include 
  
   #include 
   
    #include 
    
     #define MAX 1024    // the max storage spacetypedef int DataType;   // data type/* * sequenece queue * */typedef struct Queue {DataType *array;int front;       // pointer to the header node of queueint rear;        // pointer to the next position of last node in the queueint size;        // initial size of the queue size should be 8 bytes}Queue;Queue Q;int balance;   // should be 0, 1 -- a node add in the queuepthread_mutex_t mutex;  // mutex lockint InitQueue();int reInitQueue(uint);int get(DataType *);int put(DataType);#endif
    
   
  
 

2. queue. c

/*************************************************************************    > File Name: queue.c    > Author: wangzhicheng2013    > Mail: 2363702560@qq.com     > Created Time: Fri 14 Nov 2014 03:01:32 PM WST ************************************************************************/#include "queue.h"/* * initialize the queue * return 0 if successfully  * else return -1 * */int InitQueue() {int rc = 0;int i;Q.array = (DataType *)malloc(sizeof(DataType) * MAX);if(!Q.array) {rc = -1;printf("Init Queue failed, Memeory lack...!\n");}else {  // initialize the queueQ.front = 0;Q.size = 8;Q.rear = Q.size;for(i = 0;i < Q.size;i++) Q.array[i] = i;  pthread_mutex_init(&mutex, NULL);}return rc;}/* * reinitialize the queue * return 0 if successfully  * else return -1 * */int reInitQueue(uint capacity) {int rc = 0;int i;if(capacity >= MAX) rc = -1;else {  // initialize the queuefor(i = 2;i < capacity;i = i << 1) ;if(i > capacity) i = i / 2;  // compute the max 2 ^ n less than capacityQ.size = i;for(i = Q.rear;i < Q.size;i++) Q.array[i] = i;  Q.rear = Q.size;}return rc;}/* * get a element from the queue * return 0 if successfully  * else return -1 * */int get(DataType *e) {int rc = -1;pthread_mutex_lock(&mutex);if(balance) {   // if put a node in the queue before*e = Q.array[Q.front];Q.front = (Q.front + 1) & (Q.size - 1);  // circularly move, save much timebalance = 0; // return orginrc = 0;}pthread_mutex_unlock(&mutex);return rc;}/* * put a element in the queue * return 0 if successfully  * else return -1 * */int put(DataType e) {int rc = -1;pthread_mutex_lock(&mutex);if(!balance) {   // if the queue is balancedQ.array[Q.rear] = e;Q.rear = (Q.rear + 1) & (Q.size - 1);  // circularly move, save much timebalance = 1;rc = 0;}pthread_mutex_unlock(&mutex);return rc;}

3. main. c

/*************************************************************************    > File Name: main.c    > Author: ma6174    > Mail: ma6174@163.com     > Created Time: Fri 14 Nov 2014 03:26:48 PM WST ************************************************************************/#include "queue.h"#include 
 
  #define THREAD_NUM 20void *_read(void *arg) {DataType e;while(1) {if(get(&e)) {perror("read failed...!\n");}else printf("%d has been read...!\n", e);usleep(20);//sleep(1);}}void *_write(void *arg) {DataType e = rand() % 10;while(1) {if(put(e)) {perror("write failed...!\n");}else printf("%d has been write...!\n", e);usleep(20);//sleep(1);}}int main() {if(InitQueue()) {exit(EXIT_FAILURE);}srand((unsigned)time(NULL));pthread_t threads[THREAD_NUM];int i;for(i = 0;i < THREAD_NUM;i++) {if(i < THREAD_NUM / 2) {if(pthread_create(&threads[i], NULL, _read, NULL)) {perror("thread created failed...!\n");}}else {if(pthread_create(&threads[i], NULL, _write, NULL)) {perror("thread created failed...!\n");}}}for(i = 0;i < THREAD_NUM;i++) {pthread_join(threads[i], NULL);}return 0;}
 


4. Makefile

CC=gccall:$(CC) -g -o main src/main.c src/queue.c header/queue.h -I src/ -I header/ -lpthread

6. Run the test



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.