xref: /haiku/src/apps/haikudepot/process/ThreadedProcessNode.cpp (revision cbe0a0c436162d78cc3f92a305b64918c839d079)
1 /*
2  * Copyright 2021, Andrew Lindesay <apl@lindesay.co.nz>.
3  * All rights reserved. Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "ThreadedProcessNode.h"
8 
9 #include <unistd.h>
10 
11 #include "AbstractProcess.h"
12 #include "Logger.h"
13 
14 
15 #define TIMEOUT_UNTIL_STARTED_SECS_DEFAULT 10
16 #define TIMEOUT_UNTIL_STOPPED_SECS_DEFAULT 10
17 
18 
19 ThreadedProcessNode::ThreadedProcessNode(AbstractProcess* process,
20 		int32 startTimeoutSeconds)
21 	:
22 	AbstractProcessNode(process),
23 	fWorker(B_BAD_THREAD_ID),
24 	fStartTimeoutSeconds(startTimeoutSeconds)
25 {
26 }
27 
28 
29 ThreadedProcessNode::ThreadedProcessNode(AbstractProcess* process)
30 	:
31 	AbstractProcessNode(process),
32 	fWorker(B_BAD_THREAD_ID),
33 	fStartTimeoutSeconds(TIMEOUT_UNTIL_STARTED_SECS_DEFAULT)
34 {
35 }
36 
37 
38 ThreadedProcessNode::~ThreadedProcessNode()
39 {
40 }
41 
42 
43 /*! Considered to be protected from concurrent access by the ProcessCoordinator
44 */
45 
46 status_t
47 ThreadedProcessNode::Start()
48 {
49 	if (fWorker != B_BAD_THREAD_ID)
50 		return B_BUSY;
51 
52 	HDINFO("[Node<%s>] initiating threaded", Process()->Name());
53 
54 	fWorker = spawn_thread(&_StartProcess, Process()->Name(),
55 		B_NORMAL_PRIORITY, Process());
56 
57 	if (fWorker >= 0) {
58 		resume_thread(fWorker);
59 		return _SpinUntilProcessState(PROCESS_RUNNING | PROCESS_COMPLETE,
60 			fStartTimeoutSeconds);
61 	}
62 
63 	return B_ERROR;
64 }
65 
66 
67 status_t
68 ThreadedProcessNode::RequestStop()
69 {
70 	return Process()->Stop();
71 }
72 
73 
74 /*! This method is the initial function that is invoked on starting a new
75 	thread.  It will start a process that is part of the bulk-load.
76  */
77 
78 /*static*/ status_t
79 ThreadedProcessNode::_StartProcess(void* cookie)
80 {
81 	AbstractProcess* process = static_cast<AbstractProcess*>(cookie);
82 	bigtime_t start = system_time();
83 
84 	HDINFO("[Node<%s>] starting process in thread", process->Name());
85 	process->Run();
86 	HDINFO("[Node<%s>] finished process in thread %f seconds", process->Name(),
87 		(system_time() - start) / 1000000.0);
88 
89 	return B_OK;
90 }
91