aboutsummaryrefslogtreecommitdiff
path: root/src/tests/itoqueue1.cpp
blob: f73f4d35848ad95e739d105f8298609c8a4675f6 (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
#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;
}