⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 queue.cpp

📁 swain-0.5.2.zip的源代码,比较好用,希望大家喜欢.
💻 CPP
字号:
/*
This file is part of SWAIN (http://sourceforge.net/projects/swain).
Copyright (C) 2006  Daniel Lindstr鰉 and Daniel Nilsson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA  02110-1301, USA.
*/
#include "StdAfx.h"
#include "Queue.h"

// Maximum number of elements in the queue.
#define MAX_QUEUE	1024

Queue::Queue(void) {
	head.next = NULL;
	head.data = NULL;
	tail = &head;
	InitializeCriticalSection(&lock);
	semaphore = CreateSemaphore(NULL, 0, MAX_QUEUE, NULL);
	timeout = INFINITE;
}

Queue::~Queue(void) {
	while (!isEmpty()) {
		dequeue();
	}
	DeleteCriticalSection(&lock);
	CloseHandle(semaphore);
}

void Queue::setTimeout(unsigned long tm) {
	timeout = tm;
}

void Queue::enqueue(void *p) {
	// Allocate a new node
	Node *n = new Node();
	n->next = NULL;
	n->data = p;
	// Add the node to the back of the list
	EnterCriticalSection(&lock);
	tail->next = n;
	tail = n;
	LeaveCriticalSection(&lock);
	// Tell dequeue that the queue is nonempty
	ReleaseSemaphore(semaphore, 1, NULL);
}

void *Queue::dequeue(void) {
	// Wait until the queue is nonempty...
	if (WaitForSingleObject(semaphore, timeout) == WAIT_TIMEOUT) {
		return NULL;
	}
	// Get head and remove it from list
	EnterCriticalSection(&lock);
	Node *n = head.next;
	head.next = n->next;
	if (tail == n) {	// Removing the last node?
		tail = &head;
	}
	LeaveCriticalSection(&lock);
	// Free the memory and return the data
	void *p = n->data;
	delete n;
	return p;
}

bool Queue::isEmpty() {
	bool res;
	// Check if the front and back of the list are the same => no node between => empty
	EnterCriticalSection(&lock);
	res = (tail == &head);
	LeaveCriticalSection(&lock);
	return res;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -