The non-locking queue for multithreaded programming

Source: Internet
Author: User

About the concept and implementation of the lock-free queue, you can refer to the blog "The implementation of the lock-free queue," mainly related to the knowledge points include CAs atomic operations, chain list implementation without lock queue, array implementation of the lock-free queue and ABA problem.

The following reference to the "multi-threaded thing (no lock queue)" code, that two threads (one to add a read data) between the lock-free queue, you can not use the thread mutex method to achieve the parallel effect. The code is as follows:

#defineMax_number 1000L#defineSTATUS int#defineOK 0#defineFALSE-1typedefstruct_queue_data{intData[max_number]; intHead; inttail;} Queue_data; STATUS Push_data (Queue_data* Pqueue,intdata) {    if(NULL = =pqueue)returnERROR; if(Pqueue->head = = ((pqueue->tail) +1)%max_number)returnERROR; Pqueue->data[pqueue->tail] =data; Pqueue->tail = (Pqueue->tail +1)%Max_number; returnOK;} STATUS Pop_data (Queue_data* Pqueue,int*pData) {    if(NULL = = Pqueue | | NULL = =pData)returnERROR; if(Pqueue->head = = pqueue->tail)returnERROR; *pdata = pqueue->data[pqueue->Head]; Pqueue->head = (Pqueue->head +1)%Max_number; returnOK;}
View Code

  

Summary:

    1. The lock-free queue is only suitable for two threads in parallel, one press-in data, one popup data
    2. Lock-free queue is a parallel without locks, and there is no danger of deadlock
    3. The head and tail in the lock-free queue can only perform the self-increment operation until the end of the calculation

The non-locking queue for multithreaded programming

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.