1 /* 2 * Copyright 2013-2014, 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 // #pragma mark - JobQueue 16 17 18 JobQueue::JobQueue() 19 : 20 fMutexInitialized(false), 21 fNewJobConditionInitialized(false), 22 fJobs(), 23 fClosed(false) 24 { 25 } 26 27 28 JobQueue::~JobQueue() 29 { 30 if (fMutexInitialized) { 31 PthreadMutexLocker mutexLocker(fMutex); 32 while (Job* job = fJobs.RemoveHead()) 33 job->ReleaseReference(); 34 } 35 36 if (fNewJobConditionInitialized) 37 pthread_cond_destroy(&fNewJobCondition); 38 39 if (fMutexInitialized) 40 pthread_mutex_destroy(&fMutex); 41 } 42 43 44 status_t 45 JobQueue::Init() 46 { 47 status_t error = pthread_mutex_init(&fMutex, NULL); 48 if (error != B_OK) 49 return error; 50 fMutexInitialized = true; 51 52 error = pthread_cond_init(&fNewJobCondition, NULL); 53 if (error != B_OK) 54 return error; 55 fNewJobConditionInitialized = true; 56 57 return B_OK; 58 } 59 60 61 void 62 JobQueue::Close() 63 { 64 if (fMutexInitialized && fNewJobConditionInitialized) { 65 PthreadMutexLocker mutexLocker(fMutex); 66 fClosed = true; 67 pthread_cond_broadcast(&fNewJobCondition); 68 } 69 } 70 71 72 bool 73 JobQueue::QueueJob(Job* job) 74 { 75 PthreadMutexLocker mutexLocker(fMutex); 76 if (fClosed) 77 return false; 78 79 fJobs.Add(job); 80 job->AcquireReference(); 81 82 pthread_cond_signal(&fNewJobCondition); 83 return true; 84 } 85 86 87 Job* 88 JobQueue::DequeueJob() 89 { 90 PthreadMutexLocker mutexLocker(fMutex); 91 92 while (!fClosed) { 93 Job* job = fJobs.RemoveHead(); 94 if (job != NULL) 95 return job; 96 97 if (!fClosed) 98 pthread_cond_wait(&fNewJobCondition, &fMutex); 99 } 100 101 return NULL; 102 } 103 104 105 void 106 JobQueue::DeleteJobs(Filter* filter) 107 { 108 PthreadMutexLocker mutexLocker(fMutex); 109 110 for (JobList::Iterator it = fJobs.GetIterator(); Job* job = it.Next();) { 111 if (filter->FilterJob(job)) { 112 it.Remove(); 113 delete job; 114 } 115 } 116 } 117 118 119 // #pragma mark - Filter 120 121 122 JobQueue::Filter::~Filter() 123 { 124 } 125