Archived

This forum has been archived. Please start a new discussion on GitHub.

monitor util thread block at windows system

hi
i have a problem with monitor class at windows. I made a queue with monitor class, use notify() in put and timedwait() in get. when i have several(>20) thread to get and 1 thread to put, the thread will block. i pause the program , found one of the get thread blocked at _gate.wait() of prewait(), and another get thread blocked at _queue.wait() of postwait().

these is my test code
#include <IceUtil/Thread.h>
#include <IceUtil/Time.h>
#include <IceUtil/Monitor.h>
#include <Ice/Ice.h>
#include <iostream>
#include <list>

template<class t> class Queue: public IceUtil::Monitor<IceUtil::Mutex>
{
public:
	Queue(){};
	void put(const t & item) {
		IceUtil::Monitor<IceUtil::Mutex>::Lock lock(*this);
		_q.push_back(item);
		notify();
	}
	bool timedGet( t & ret, const IceUtil::Time& timeout)
	{
		IceUtil::Monitor<IceUtil::Mutex>::Lock lock(*this);
		if (_q.size() == 0)
			timedWait(timeout);
		if (_q.size() == 0)
		{
			return false;
		}
		ret = _q.front();
		_q.pop_front();
		return true;
	}
private:
	std::list<t> _q;
};

Queue<int> m_pQ;
class testthread : public IceUtil::Thread
{

public:
	virtual void run()
	{
		int n = 0;
		srand((int)IceUtil::Time::now().toMicroSeconds());
		while(true)
		{
			int Result;
			int nTime = rand() % 1000;
			m_pQ.timedGet(Result, IceUtil::Time::microSeconds(nTime) );
			Sleep(10);
			std::cout << nTime << " ";
		}
	}
};
void main()
{
	for (int i = 0; i < 100; i++)
	{
		testthread* p = new testthread;
		p->start();
	}
	while(true)
	{
		m_pQ.put(2);
		Sleep(1);
	}
	return;
}

Comments