Multi-thread (lock-free queue)

Source: Internet
Author: User

[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.

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.