summaryrefslogtreecommitdiff
path: root/src/tests/itoqueue1.cpp
blob: 5dbfd16d1478e2692c40ca4f4212ec9e15104718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
 * Copyright (C) 2007 Xagasoft, All rights reserved.
 *
 * This file is part of the libbu++ library and is released under the
 * terms of the license contained in the file LICENSE.
 */

#include <string>
#include "bu/ito.h"
#include "bu/itoqueue.h"

class Reader : public Bu::Ito
{
public:
	Reader( Bu::ItoQueue<std::string *> &q, int id ) :
		q( q ),
		id( id )
	{
	}

	void *run()
	{
		for( int i = 0; i < 10; i++ )
		{
			std::string *pStr = q.dequeue( true );
			if( pStr == NULL )
			{
				printf("Null received...\n");
			}
			else
			{
				printf("[%d] read:  %s\n", id, pStr->c_str() );
				delete pStr;
			}
			usleep( (int)(((double)rand())/((double)RAND_MAX)*2000000.0) );
		}

		return NULL;
	}

private:
	Bu::ItoQueue<std::string *> &q;
	int id;
};

class Writer : public Bu::Ito
{
public:
	Writer( Bu::ItoQueue<std::string *> &q, int id, const char *strbase ) :
		q( q ),
		strbase( strbase ),
		id( id )
	{
	}

	void *run()
	{
		for( int i = 0; i < 11; i++ )
		{
			usleep( (int)(((double)rand())/((double)RAND_MAX)*2000000.0) );
			q.enqueue( new std::string( strbase ) );
			printf("[%d] write: %s\n", id, strbase );
		}

		return NULL;
	}

private:
	Bu::ItoQueue<std::string *> &q;
	const char *strbase;
	int id;
};

int main()
{
	Writer *wr[5];
	Reader *rd[5];
	const char bob[][7]={
		{"Test 1"},
		{"Test 2"},
		{"Test 3"},
		{"Test 4"},
		{"Test 5"}
	};

	Bu::ItoQueue<std::string *> q;

	for( int j = 0; j < 5; j++ )
	{
		wr[j] = new Writer( q, j, bob[j] );
		rd[j] = new Reader( q, j );
	}

	for( int j = 0; j < 5; j++ )
	{
		rd[j]->start();
	}

	for( int j = 0; j < 5; j++ )
	{
		wr[j]->start();
	}

	for( int j = 0; j < 5; j++ )
	{
		rd[j]->join();
	}

	for( int j = 0; j < 5; j++ )
	{
		delete wr[j];
		delete rd[j];
	}

	return 0;
}