[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
For friends who write multiple threads, queues are inherently mutually exclusive. In the queue, one is responsible for adding data and the other is responsible for processing data. No one can hinder anyone, and no one can do without anyone. Therefore, queues are inherently parallel.
#define MAX_NUMBER 1000L#define STATUS int#define OK 0#define FALSE -1typedef struct _QUEUE_DATA{ int data[MAX_NUMBER]; int head; int tail;}QUEUE_DATA;
At this time, a thread is pressed into data and the operation is push_data,
STATUS push_data(QUEUE_DATA* pQueue, int data){ if(NULL == pQueue) return ERROR; if(pQueue->head == ((pQueue->tail) + 1)% MAX_NUMBER) return ERROR; pQueue->data[pQueue->tail] = data; pQueue->tail = (pQueue->tail + 1)% MAX_NUMBER; return OK;}
Another thread is responsible for processing data pop_data,
STATUS pop_data(QUEUE_DATA* pQueue, int* pData){ if(NULL == pQueue || NULL == pData) return ERROR; if(pQueue->head == pQueue->tail) return ERROR; *pData = pQueue->data[pQueue->head]; pQueue->head = (pQueue->head + 1)% MAX_NUMBER; return OK;}
Summary:
(1) The queue is only suitable for parallel use by two threads. One is pushed into data, and the other is pushed out data.
(2) The queue is parallel without locks and there is no danger of deadlock.
(3) in the queue, the head and tail operations can only be performed before the calculation ends.