#include <list>
using namespace std;
const int thread_cycles = 10;
const int thread_pairs = 10;
const unsigned max_size = 100;
const int iters = 10000;
class task_queue
{
public:
task_queue ()
{
pthread_mutex_init (&fooLock, NULL);
pthread_cond_init (&fooCond1, NULL);
pthread_cond_init (&fooCond2, NULL);
}
~task_queue ()
{
pthread_mutex_destroy (&fooLock);
pthread_cond_destroy (&fooCond1);
pthread_cond_destroy (&fooCond2);
}
list<int> foo;
pthread_mutex_t fooLock;
pthread_cond_t fooCond1;
pthread_cond_t fooCond2;
};
void*
produce (void* t)
{
task_queue& tq = *(static_cast<task_queue*> (t));
int num = 0;
while (num < iters)
{
pthread_mutex_lock (&tq.fooLock);
while (tq.foo.size () >= max_size)
pthread_cond_wait (&tq.fooCond1, &tq.fooLock);
tq.foo.push_back (num++);
pthread_cond_signal (&tq.fooCond2);
pthread_mutex_unlock (&tq.fooLock);
}
return 0;
}
void*
consume (void* t)
{
task_queue& tq = *(static_cast<task_queue*> (t));
int num = 0;
while (num < iters)
{
pthread_mutex_lock (&tq.fooLock);
while (tq.foo.size () == 0)
pthread_cond_wait (&tq.fooCond2, &tq.fooLock);
if (tq.foo.front () != num++)
abort ();
tq.foo.pop_front ();
pthread_cond_signal (&tq.fooCond1);
pthread_mutex_unlock (&tq.fooLock);
}
return 0;
}
#if !__GXX_WEAK__ && _MT_ALLOCATOR_H
template class __gnu_cxx::__mt_alloc<std::_List_node<int> >;
#endif
int
main ()
{
pthread_t prod[thread_pairs];
pthread_t cons[thread_pairs];
task_queue* tq[thread_pairs];
#if defined(__sun) && defined(__svr4__) && _XOPEN_VERSION >= 500
pthread_setconcurrency (thread_pairs * 2);
#endif
for (int j = 0; j < thread_cycles; j++)
{
for (int i = 0; i < thread_pairs; i++)
{
tq[i] = new task_queue;
pthread_create (&prod[i], NULL, produce, static_cast<void*> (tq[i]));
pthread_create (&cons[i], NULL, consume, static_cast<void*> (tq[i]));
}
for (int i = 0; i < thread_pairs; i++)
{
pthread_join (prod[i], NULL);
pthread_join (cons[i], NULL);
delete tq[i];
}
}
return 0;
}