1 // Copyright 2006 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // queue.cc : simple thread safe queue implementation
19 // This file must work with autoconf on its public version,
20 // so these includes are correct.
24 // Page entry queue implementation follows.
25 // Push inserts pages, pop returns a random entry.
28 PageEntryQueue::PageEntryQueue(uint64 queuesize) {
29 // There must always be one empty queue location,
30 // since in == out => empty.
31 q_size_ = queuesize + 1;
32 pages_ = new struct page_entry[q_size_];
37 pthread_mutex_init(&q_mutex_, NULL);
39 PageEntryQueue::~PageEntryQueue() {
41 pthread_mutex_destroy(&q_mutex_);
44 // Add a page into this queue.
45 int PageEntryQueue::Push(struct page_entry *pe) {
52 pthread_mutex_lock(&q_mutex_);
53 nextnextin = (nextin_ + 1) % q_size_;
55 if (nextnextin != nextout_) {
56 pages_[nextin_] = *pe;
64 pthread_mutex_unlock(&q_mutex_);
69 // Retrieve a random page from this queue.
70 int PageEntryQueue::PopRandom(struct page_entry *pe) {
75 struct page_entry tmp;
80 // TODO(nsanders): we should improve random to get 64 bit randoms, and make
81 // it more thread friendly.
82 uint64 rand = random();
84 int retval = pthread_mutex_lock(&q_mutex_);
86 logprintf(0, "Process Error: pthreads mutex failure %d\n", retval);
89 if (nextin_ != nextout_) {
91 // Swap random entry with next out.
93 lastin = (nextin_ - 1 + q_size_) % q_size_;
94 entries = (lastin - nextout_ + q_size_) % q_size_;
98 newindex = ((rand % entries) + nextout_) % q_size_;
101 tmp = pages_[nextout_];
102 pages_[nextout_] = pages_[newindex];
103 pages_[newindex] = tmp;
106 // Return next out page.
107 *pe = pages_[nextout_];
109 nextout_ = (nextout_ + 1) % q_size_;
115 pthread_mutex_unlock(&q_mutex_);