-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.hpp
66 lines (53 loc) · 1.47 KB
/
writer.hpp
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
#include <fstream>
#include <cassert>
#include "thread.hpp"
#include "ts_queue.hpp"
#include "item.hpp"
#ifndef WRITER_HPP
#define WRITER_HPP
// Writer runs in a thread that reads Item from the Output Queue then writes Items into the output file.
class Writer : public Thread
{
public:
// constructor
Writer(int expected_lines, std::string output_file, TSQueue<Item *> *output_queue);
// destructor
~Writer();
virtual void start() override;
private:
// the expected lines to write,
// the writer thread finished after output expected lines of item
int expected_lines;
std::ofstream ofs;
TSQueue<Item *> *output_queue;
// the method for pthread to create a writer thread
static void *process(void *arg);
};
// Implementation start
Writer::Writer(int expected_lines, std::string output_file, TSQueue<Item *> *output_queue)
: expected_lines(expected_lines), output_queue(output_queue)
{
ofs = std::ofstream(output_file);
}
Writer::~Writer()
{
ofs.close();
}
void Writer::start()
{
// pass this, so the thread can access the same Writer instance
assert(!pthread_create(&t, nullptr, &Writer::process, static_cast<void *>(this)));
}
void *Writer::process(void *arg)
{
// this is a static method, we have to specify the Writer instance
Writer *writer = static_cast<Writer *>(arg);
while (writer->expected_lines--) // end after writing all lines
{
Item *item = writer->output_queue->dequeue();
writer->ofs << *item;
delete item;
}
return nullptr;
}
#endif // WRITER_HPP