-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
138 lines (126 loc) · 2.49 KB
/
main.cpp
File metadata and controls
138 lines (126 loc) · 2.49 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "nlqueue.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
bool allExit(false);
int prod(const string &num, NoLockRing *ring)
{
FILE *file = fopen(num.c_str(), "w+");
if (!file)
{
cerr << this_thread::get_id() << ", open file: " << num << ", error." << endl;
return -1;
}
int maxLen(100);
int size(1000000);
int total(0);
for (int i = 0; i < size; ++i)
{
int len = random() % maxLen;
if (len < 10)
len = 10;
char *p = (char*)malloc(len + 1);
if (!p)
{
cerr << "prod malloc null" << endl;
break;
}
memset(p, 0, len + 1);
for (int j = 0; j < len; ++j)
{
char c = random() % 26 + 'a';
*p++ = c;
fwrite(&c, 1, 1, file);
}
p -= len;
while (ring->push(p) <= 0 )
{
//cout << "ring is full, wait!" << total << endl;
this_thread::sleep_for(chrono::milliseconds(5));
fflush(file);
}
fwrite("\n", 1, 1, file);
++total;
}
fclose(file);
}
int cons(const string &num, NoLockRing *ring)
{
FILE *file = fopen(num.c_str(), "w+");
if (!file)
{
cerr << this_thread::get_id() << ", open file: " << num << ", error." << endl;
return -1;
}
char **p = (char**)malloc(40);
if(!p)
{
cerr << "cons malloc null" << endl;
fclose(file);
return -1;
}
int total(0);
int nexit(1);
while (1)
{
int ret = ring->pop(5, (void**)p);
if (ret <= 0)
{
this_thread::sleep_for(chrono::milliseconds(5));
fflush(file);
if (allExit && (nexit-- <= 0))
{
cerr << "ring is empty,exit, total: " << total << endl;
break;
}
continue;
}
for (int i =0; i<ret; ++i)
{
if (!p[i])
{
cerr << i << ", error" << endl;
continue;
}
fwrite(p[i], strlen(p[i]), 1, file);
fwrite("\n", 1, 1, file);
free(p[i]);
++total;
}
}
free(p);
fclose(file);
}
int main()
{
NoLockRing *ring = new NoLockRing(1024, RING_MP | RING_MC);
if (!ring)
{
cerr << "new ring error" << endl;
return -1;
}
if (ring->init())
{
delete ring;
return -1;
}
int num(2);
thread th[num];
for (int i = 0; i < num; ++i)
th[i] = thread(prod, string("a").append(to_string(i)), ring);
thread con[num];
for (int i = 0; i < num; ++i)
con[i] = thread(cons, string("b").append(to_string(i)), ring);
for (int i = 0; i < num; ++i)
th[i].join();
allExit = true;
for (int i = 0; i < num; ++i)
con[i].join();
delete ring;
return 0;
}