Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- An implemention of a Queue.
- The queue is designed to be able to work with multiple threads.
- You can have multiple thread put to thead the Queue will automaticly block if another thread is putting to the queue.
- If you want to have mutiple threads read data from queue the reading threads will need to be sure to block themself.
- To Create a queue
- ---
- Queue!string queue; // Replace string with data type that values should be.
- ---
- To add to queue
- ---
- queue.put("This is a value that is added to queue!"); // Argument should be of oppropriate type.
- ---
- To read data
- ---
- foreach (string value; queue) {
- // Deal with value here!
- }
- ---
- To read data safe to have multiple threads reading
- ---
- synchronized {
- foreach (string value; queue) {
- // Deal with value here!
- }
- }
- ---
- or
- ---
- while (true) {
- string value;
- synchronized {
- if (queue.empty) {
- break;
- }
- value = queue.front;
- queue.popFront;
- }
- // Deal with value here!
- }
- ---
- Examples:
- ---
- Queue!string queue;
- queue.add("A!");
- queue.add("BBB!");
- queue.add("CC!");
- foreach (string value; queue) {
- writeln(value);
- }
- queue.add("DDDDD!");
- queue.add("EEEE!");
- foreach (string value; queue) {
- writeln(value);
- }
- ---
- */
- module queue;
- import std.stdio;
- ////import core.sync.semaphore : Semaphore;
- class Queue(T) {
- //private struct HeadNode {
- // Node* _first;
- //}
- private struct Node {
- T payload;
- Node* next;
- }
- private Node* _first;
- private Node* _last = new Node(null,null);
- private int count = 0;
- private Object countLock = new Object;
- this() {
- this._first = this._last;
- }
- /**
- Add to the Queue (to the end).
- */
- void put(T value) {
- synchronized {
- Node* newLast = new Node(null,null);
- this._last.payload = value;
- this._last.next = newLast;
- this._last = newLast;
- synchronized(countLock) {
- count++;
- }
- }
- }
- /**
- To be iterable with `foreach` loop.
- */
- bool empty() const {
- return this.count == 0;
- ////return _head._first == null;
- }
- ///ditto
- void popFront() {
- assert (!this.empty);
- this._first = this._first.next;
- synchronized(countLock) {
- count--;
- }
- }
- ///ditto
- T front() const {
- assert (!this.empty);
- return this._first.payload;
- ////}
- ////else {
- //// return null;
- ////}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement