xref: /haiku/src/servers/package/JobQueue.cpp (revision 225b6382637a7346d5378ee45a6581b4e2616055)
1 /*
2  * Copyright 2013, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Ingo Weinhold <ingo_weinhold@gmx.de>
7  */
8 
9 
10 #include "JobQueue.h"
11 
12 #include <PthreadMutexLocker.h>
13 
14 
15 JobQueue::JobQueue()
16 	:
17 	fMutexInitialized(false),
18 	fNewJobConditionInitialized(false),
19 	fJobs(),
20 	fClosed(false)
21 {
22 }
23 
24 
25 JobQueue::~JobQueue()
26 {
27 	if (fMutexInitialized) {
28 		PthreadMutexLocker mutexLocker(fMutex);
29 		while (Job* job = fJobs.RemoveHead())
30 			job->ReleaseReference();
31 	}
32 
33 	if (fNewJobConditionInitialized)
34 		pthread_cond_destroy(&fNewJobCondition);
35 
36 	if (fMutexInitialized)
37 		pthread_mutex_destroy(&fMutex);
38 }
39 
40 
41 status_t
42 JobQueue::Init()
43 {
44 	status_t error = pthread_mutex_init(&fMutex, NULL);
45 	if (error != B_OK)
46 		return error;
47 	fMutexInitialized = true;
48 
49 	error = pthread_cond_init(&fNewJobCondition, NULL);
50 	if (error != B_OK)
51 		return error;
52 	fNewJobConditionInitialized = true;
53 
54 	return B_OK;
55 }
56 
57 
58 void
59 JobQueue::Close()
60 {
61 	if (fMutexInitialized && fNewJobConditionInitialized) {
62 		PthreadMutexLocker mutexLocker(fMutex);
63 		fClosed = true;
64 		pthread_cond_broadcast(&fNewJobCondition);
65 	}
66 }
67 
68 
69 bool
70 JobQueue::QueueJob(Job* job)
71 {
72 	PthreadMutexLocker mutexLocker(fMutex);
73 	if (fClosed)
74 		return false;
75 
76 	fJobs.Add(job);
77 	job->AcquireReference();
78 
79 	pthread_cond_signal(&fNewJobCondition);
80 	return true;
81 }
82 
83 
84 Job*
85 JobQueue::DequeueJob()
86 {
87 	PthreadMutexLocker mutexLocker(fMutex);
88 
89 	while (!fClosed) {
90 		Job* job = fJobs.RemoveHead();
91 		if (job != NULL)
92 			return job;
93 
94 		if (!fClosed)
95 			pthread_cond_wait(&fNewJobCondition, &fMutex);
96 	}
97 
98 	return NULL;
99 }
100