node-pdfutils
PdfWorker.h
1 /*
2  * PdfWorker.h
3  * Copyright (C) 2014 tox <tox@rootkit>
4  *
5  * Distributed under terms of the MIT license.
6  */
7 
8 #ifndef PDFWORKER_H
9 #define PDFWORKER_H
10 
11 #include <nan.h>
12 #include <uv.h>
13 #include <list>
14 #include "../PdfController.h"
15 
16 
20 template <class T>
21 class PdfWorker : public NanAsyncWorker {
22 private:
23  T *_controller;
24  uv_async_t *async;
25  uv_mutex_t mutex;
26  std::list<void *> intermediate;
27 
34  static void handleIntermediate(uv_async_t *handle) {
35  PdfWorker *self = (PdfWorker *)handle->data;
36  void *data;
37 
38  while(true) {
39  uv_mutex_lock(&self->mutex);
40  if(self->intermediate.empty()) {
41  uv_mutex_unlock(&self->mutex);
42  break;
43  } else {
44  data = self->intermediate.front();
45  self->intermediate.pop_front();
46  uv_mutex_unlock(&self->mutex);
47  }
48  self->HandleIntermediate(data);
49  }
50  }
51 
58  static void deleteAsync(uv_handle_t* handle) {
59  // handle points to the same location as this->async. but at this point
60  // the object is already freed, so we only dereference the handle here.
61  delete (uv_async_t *)handle;
62  }
63 
64 public:
65  PdfWorker(T *controller, NanCallback *callback) : NanAsyncWorker(callback) {
66  _controller = controller;
67 
68  if(callback) {
69  uv_loop_t *loop = uv_default_loop();
70  this->async = new uv_async_t;
71  uv_async_init(loop, this->async, reinterpret_cast<uv_async_cb>(handleIntermediate));
72  this->async->data = this;
73  uv_mutex_init(&mutex);
74  }
75  }
76 
77  ~PdfWorker() {
78  if(this->callback == NULL)
79  return;
80  uv_close((uv_handle_t*)this->async, deleteAsync);
81  uv_mutex_destroy(&this->mutex);
82  this->async = NULL;
83  }
84 
85  T *controller() {
86  return _controller;
87  }
88 
89  void CallIntermediate(void *data) {
90  uv_mutex_lock(&this->mutex);
91  intermediate.push_back(data);
92  uv_mutex_unlock(&this->mutex);
93  }
94 
95  virtual void HandleIntermediate(void *data) {}
96 };
97 
98 #endif /* !PDFWORKER_H */
Base class for defining background processes.
Definition: PdfWorker.h:21