-
Notifications
You must be signed in to change notification settings - Fork 4
/
processpool.h
109 lines (89 loc) · 2.76 KB
/
processpool.h
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
#pragma once
#ifndef INTERNAL_PROCESS_POOL_H
#define INTERNAL_PROCESS_POOL_H
#include <string>
#include <vector>
#include <queue>
#include <map>
#include "disallow_copy_and_assign.h"
#ifdef _WIN32
#include <windows.h>
class OSProcess {
public:
OSProcess(const std::string &worker_path);
~OSProcess();
std::string WaitForChildMessage();
void SendMessageToChild(const std::string &msg);
private:
HANDLE read_pipe_;
HANDLE write_pipe_;
PROCESS_INFORMATION process_info_;
DISALLOW_COPY_AND_ASSIGN(OSProcess);
};
#else
#include <unistd.h>
class OSProcess {
public:
OSProcess(const std::string &worker_path);
~OSProcess();
std::string WaitForChildMessage();
void SendMessageToChild(const std::string &msg);
private:
int read_pipe_;
int write_pipe_;
int process_info_;
DISALLOW_COPY_AND_ASSIGN(OSProcess);
};
#endif //_WIN32
class ProcessPool;
class ProcessHandle {
public:
void Process(const std::string& task);
inline bool idle(){return idle_;}
void ProcessInBackground();
ProcessHandle(const std::string &worker_path, ProcessPool* parent_process_pool);
private:
bool idle_;
OSProcess os_process_;
ProcessPool* parent_process_pool_;
bool ProcessMessageFromChild(const std::string& msg);
DISALLOW_COPY_AND_ASSIGN(ProcessHandle);
};
class ProcessPool {
public:
// Change number of process handlers
void Resize(int _size);
typedef int (*JobFunctionPtr)(int argc, const char* argv[]);
typedef std::map<std::string, ProcessPool::JobFunctionPtr> JobMap;
enum Error{SUCCESS = 0,
NO_IDLE_PROCESS = -1,
NO_TASK_IN_QUEUE = -2};
static bool AmIAWorkerProcess( int argc, char* argv[] );
static int WorkerProcessMain(const JobMap &job_map);
void NotifyTaskComplete();
void Schedule(const std::string& task);
void WaitForTasksToComplete();
ProcessPool(const std::string &worker_path, int size=0);
~ProcessPool();
private:
// Attempts to start processing the first task in the queue in the first
// idle process. Can return SUCCESS, NO_IDLE_PROCESS or NO_TASK_IN_QUEUE.
ProcessPool::Error ProcessFirstTaskInQueue();
// Returns index of the first idle process in pool, or -1 if there
// are no idle processes
int GetIdleProcessIndex();
std::string worker_path_;
std::vector<ProcessHandle*> processes_;
std::queue<std::string> tasks_;
#ifdef _WIN32
HANDLE mutex_;
HANDLE idle_event_;
#else
pthread_mutex_t mutex_;
pthread_mutex_t idle_event_mutex_;
pthread_cond_t idle_event_cond_;
bool idle_event_bool_;
#endif
DISALLOW_COPY_AND_ASSIGN(ProcessPool);
};
#endif //INTERNAL_PROCESS_POOL_H