I tried to create a lock free atomic circular queue but it is not working properly.
I created 2 threads. One is for pushing into queue and another one is for popping from the queue. But;
Problem: -When push thread running then pop thread does not get chance to run. Pop thread runs after push thread runs completely and vice versa.
I do not know much about C++. So, please can you edit my code so that it works?
I am using GCC 4.8.1
Thanks in advance.
Code:
#include <cstdlib>
#include <iostream>
#include <atomic>
#include <cstddef>
#include <thread>
#include <stdio.h>
#include <unistd.h>
#define capacity 1000
std::atomic<int> _head;
std::atomic<int> _tail;
int array[capacity];
int increment(int size)
{
return (size+1)%capacity;
}
bool push(int *item)
{
printf("Inside push\n");
const int current_tail= _tail.load(std::memory_order_relaxed);
const int next_tail=increment(current_tail);
if(next_tail != _head.load(std::memory_order_acquire))
{
array[current_tail]=*item;
_tail.store(next_tail,std::memory_order_release);
return true;
}
return false; //Queue is Full
}
bool pop(int *item)
{
printf("Inside pop\n");
const int current_head=_head.load(std::memory_order_relaxed);
if(current_head==_tail.load(std::memory_order_acquire))
{
return false;//empty queue
}
*item=array[current_head];
_head.store(increment(current_head),std::memory_order_release);
return true;
}
bool isEmpty()
{
return(_head.load()==_tail.load());
}
bool isFull()
{
const int next_tail=increment(_tail);
return (next_tail==_head.load());
}
bool isLockfree()
{
return (_tail.is_lock_free() && _head.is_lock_free());
}
void *threadfunction_push()
{
int item,i;
bool flag;
item=0;
for(i=0;i<10000;i++)
{
while(isFull())
std::this_thread::yield();
++item;
push(&item);
printf("pushed %d into queue\n",item);
//usleep(100);
}
}
void *threadfunction_pop()
{
int item,i;
item=0;
for(i=0;i<10000;i++)
{
while(isEmpty())
std::this_thread::yield();
pop(&item);
printf("popped %d from queue\n",item);
}
i=isLockfree();
if(i)
printf("Queue is lock Free");
}
int main(int argc, char** argv)
{
std::thread thread_push(threadfunction_push);
std::thread thread_pop(threadfunction_pop);
thread_push.join();
thread_pop.join();
return 0;
}
isEmpty
suggests you need a better understanding of the basic idea of concurrent programming, possibly from a textbook. – DanielKO