lundi 23 février 2015

Deadlock C++11 Thread

I am implementing one thread safe queue. And i am having some problems.


I have one function "wait_pop", that will do pop in the queue if the queue isn't empty. If the queue is empty, will block.


This is the code:



class queue{

//...

std::queue<T> Cola;
std::condition_variable Variable;
mutable std::mutex Cerrojo;

void waitSomething(std::unique_lock<std::mutex> &e,std::condition_variable &Condition,
bool (queue<T>::*predicate)() const)
{
while (((*this).*predicate)())
{
Condition.wait(e);
}
}

void consumer_enterprotocol(std::unique_lock<std::mutex> &e)
{
waitSomething(e,Variable_Push,&queue<T>::empty_nothreadsafe);
}

void producer_exitprotocol(std::unique_lock<std::mutex> &e)
{
e.unlock();
Variable.notify_one();
}

bool empty_nothreadsafe() const noexcept
{
return Cola.empty();
}

//PUBLIC...

void push(const T &element)
{
unique_lock<std::mutex> e(Cerrojo);
producer_enterprotocol(e);
Cola.push(element);
producer_exitprotocol(e);
}

void wait_pop(T &element)
{
unique_lock<std::mutex> e(Cerrojo);
consumer_enterprotocol(e);
pop_nothreadsafe(element);
consumer_exitprotocol(e);
}


And the test code:



#include <iostream>
#include "STL Threadsafe/queue thread safe.hpp"

std::threadsafe::queue<int> Cola;

int max = 200;
void hilo()
{
for (int i = 0;i<max;i++)
{
Cola.push(i);
}
}

int main()
{
int e = 0;
std::thread t(hilo);
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
for (int i = 0;i<max;i++)
{
Cola.wait_pop(e);
std::cout<<e<<std::endl;
}
std::cout<<"End: "<<Cola.size()<<std::endl;
t.join();
}


This code does infinite wait in wait_pop. If I put one sleep (check the commented line), code will works properly (why?). I have been checking but i don't get it.


I can give full code if you want compile. Full code is a bit more complicated that this, methods are in lineal_container, not in queue: http://ift.tt/1FPi7iH


Aucun commentaire:

Enregistrer un commentaire