-
Notifications
You must be signed in to change notification settings - Fork 5
/
BigQ.cc
269 lines (249 loc) · 8.5 KB
/
BigQ.cc
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#include "BigQ.h"
#include <vector>
#include <queue>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <utility>
#include <algorithm>
#include <cassert>
#include <iterator>
#include <omp.h>
/* Morgan Bauer */
BigQ :: BigQ (Pipe & _in, Pipe & _out, OrderMaker & _sortorder, int _runlen)
: in(_in),out(_out),sortorder(_sortorder),runlen(_runlen), pagesInserted(0), totalRecords(0), runCount(0), partiallySortedFile(), runLocations(), worker_thread()
{
pthread_create (&worker_thread, NULL, &BigQ::thread_starter, this);
}
// don't declare static
// http://cplusplus.syntaxerrors.info/index.php?title=Cannot_declare_member_function_%E2%80%98static_int_Foo::bar%28%29%E2%80%99_to_have_static_linkage
void * BigQ :: thread_starter(void *context)
{
return reinterpret_cast<BigQ*>(context)->WorkerThread();
}
void * BigQ :: WorkerThread(void) {
// cout << endl << "BIGQ STARTED" << endl;
char partiallySortedFileTempFileName[] = "/tmp/partiallysortedXXXXXX"; // maybe set this per instance to a random filename
partiallySortedFile.TempOpen(partiallySortedFileTempFileName);
clog << "using tempfile in " << partiallySortedFileTempFileName << endl;
// FIRST PHASE
clog << "sorting with " << runlen << " pages of memory" << endl;
PhaseOne();
// in pipe should be dead now.
// SECOND PHASE
static const int runThreshold = 200;
clog << "sorting " <<runCount << " runs with " << runlen << " pages of memory" << endl;
if (runThreshold >= runCount)
{
PhaseTwoLinearScan();
}
else
{
PhaseTwoPriorityQueue();
}
out.ShutDown ();
clog << endl << "MERGE COMPLETE" << endl;
// Cleanup
partiallySortedFile.Close();
clog << "deleting tempfile in " << partiallySortedFileTempFileName << endl;
int ret = remove(partiallySortedFileTempFileName);
if (ret)
perror ("The following error occurred");
// finally shut down the out pipe
// this lets the consumer thread know that there will not be anything else put into the pipe
pthread_exit(NULL); // make our worker thread go away
}
void BigQ::PhaseOne(void)
{
size_t vecsize = runlen; //good first guess
// FIRST PHASE
// read data from in pipe sort them into runlen pages
vector<Record> runlenrecords;
runlenrecords.reserve(vecsize);
Record tempRecord;
static size_t const maxSize = PAGE_SIZE * runlen;
size_t curSize = 0;
while (1 == in.Remove(&tempRecord)) // while we can take records out of the pipe, do so.
{
curSize += tempRecord.GetSize();
if (curSize <= maxSize) // have more room in the buffer
{
runlenrecords.push_back(tempRecord); // put it in our runlen sized buffer.
}
else // have runlen pages of records
{
runCount++;
// update probable max vector size to avoid copying in future iterations.
if (vecsize < runlenrecords.size()) {vecsize = runlenrecords.size();}
sortRuns(runlenrecords);
writeSortedRunToFile(runlenrecords);
runlenrecords.clear(); // reset the temp vector buffer thing
curSize = 0;
runlenrecords.push_back(tempRecord);// put the new record in
}
}
// we've taken all the records out of the pipe
// do one last internal sort, on the the buffer that we have
if (0 < runlenrecords.size())
{
if (vecsize < runlenrecords.size()) {vecsize = runlenrecords.size();}
runCount++;
sortRuns(runlenrecords);
// cout << "last run sorted " << endl;
writeSortedRunToFile(runlenrecords);
}
}
void BigQ :: sortRuns(vector<Record> & runlenrecords)
{
// sort the records we have in the runlen buffer.
Compare c = Compare(sortorder);
// if (!std::is_sorted(runlenrecords.begin(),
// runlenrecords.end(),
// c))
{
std::sort(runlenrecords.begin(),
runlenrecords.end(),
c);
}
}
int BigQ :: writeSortedRunToFile(vector<Record> & runlenrecords)
{
off_t pageStart = pagesInserted;
// now to write sorted records out to a file, first, we must fill a page ...
Page tp;
Record trp;
for (vector<Record>::iterator it = runlenrecords.begin(); it < runlenrecords.end(); it++)
{
totalRecords++;
trp.Consume(&(*it));
if(0 == tp.Append(&trp))
{
partiallySortedFile.AddPage(&tp,pagesInserted++);
tp.EmptyItOut();
tp.Append(&trp);
}
}
partiallySortedFile.AddPage(&tp,pagesInserted++);
off_t pageEnd = pagesInserted;
// cout << "inserted " << pageEnd - pageStart << " pages" << endl;
runLocations.push_back(make_pair(pageStart,pageEnd));
return (int)(pageEnd-pageStart);
}
void BigQ::PhaseTwoLinearScan(void)
{
clog << endl << endl << "Linear Scan Merge of sorted runs" << endl;
{
vector<Run> runs;
runs.reserve(runCount);
//initializing runs
for (int i = 0; i < runCount; i++)
{
runs.push_back(Run(i,runLocations[i].first,runLocations[i].second, &partiallySortedFile)); // maybe try enplace from c++11
}
vector<Record> minimums;
// initialize minimums
// for each run, get the first guy.
minimums.reserve(runCount); // we know how many runs we are merging, so reserve that much space from the beginning to avoid the vector reallocation
for (int i = 0; i < runCount; i++)
{
Record tr;
runs[i].getNextRecord(tr);
minimums.push_back(tr);
}
// now find the minimum guy and put it in the pipe
// do this totalRecords times
Compare c = Compare(sortorder);
{
int runsLeft = runCount;
int recordsOut = 0;
for (int r = totalRecords ; r > 0; r--) // I know exactly how many records I have, so iterate that many times.
{
vector<Record>::iterator::difference_type run =
std::distance( minimums.begin(),
std::min_element(minimums.begin(), minimums.end(), c));
out.Insert(&(minimums[run]));
if (!runs[run].getNextRecord((minimums[run]))) // run empty, got to get rid of it
{ // need to get rid of run and shift everything over
runsLeft--;
minimums.erase(minimums.begin() + run);
runs.erase(runs.begin() + run);
}
recordsOut++;
if (0 == recordsOut % 10000)
{
clog << recordsOut/10000 << " ";
}
}
assert(recordsOut == totalRecords);
assert (0 == runsLeft);
}
}
}
void BigQ::PhaseTwoPriorityQueue(void)
{
cout << endl << endl << "Priority Queue Merge of sorted runs" << endl;
{
vector<Run> runs;
runs.reserve(runCount);
// cout << "initializing runs" << endl;
for (int i = 0; i < runCount; i++)
{
// cout << "Run " << i;
runs.push_back(Run(i,runLocations[i].first,runLocations[i].second, &partiallySortedFile));
// cout << " initialized" << endl;
}
for (int i = 0; i < runCount; i++)
{
// runs[i].print();
}
std::priority_queue<TaggedRecord, vector<TaggedRecord>, TaggedRecordCompare> mins (sortorder);
// initialize minimums
// for each run, get the first guy.
// cout << "initializing minimums" << endl;
// minimums.reserve(runCount);
for (int i = 0; i < runCount; i++)
{
// cout << "minimum " << i;
Record tr;
runs[i].getNextRecord(tr);
// minimums.push_back(tr);
// cout << "push" << endl;
mins.push(TaggedRecord(tr,i));
// cout << "initialized " << endl;
}
// now find the minimum guy and put it in the pipe
// do this totalRecords times
// cout << "putting stuff in the pipe" << endl;
// Compare c = Compare(sortorder);
{
int runsLeft = runCount;
int recordsOut = 0;
for (int r = totalRecords ; r > 0; r--)
{
TaggedRecord TRtr(mins.top());
Record tr(TRtr.r);
int run = TRtr.getRun();
recordsOut++;
out.Insert(&tr);
mins.pop();
bool valid = runs[run].getNextRecord(tr);
if (valid)
{
mins.push(TaggedRecord(tr,run));
}
else
{
// cout << "run empty, got to get rid of it" << endl;
runsLeft--;
}
}
assert(recordsOut == totalRecords);
// cout << "runs left = "<< runsLeft << endl;
assert (0 == runsLeft);
}
}
// cout << runCount << " runs in " << partiallySortedFile.GetLength() << " total pages" << endl;
// cout << "runlen of " << runlen << endl;
// cout << "phase two complete" << endl;
}
BigQ::~BigQ () {}