1 /**
2 Module with multithreaded vectors.
3  */
4 module mutils.container_shared.shared_vector;
5 
6 import std.algorithm : remove;
7 import std.experimental.allocator;
8 import std.experimental.allocator.mallocator;
9 
10 import mutils.container.vector;
11 
12 ////////////////////
13 
14 class LockedVectorBuildIn(T) {
15 	T[] array;
16 public:
17 	bool empty() {
18 		return (array.length == 0);
19 	}
20 
21 	void add(T t) {
22 		synchronized (this) {
23 			array.assumeSafeAppend ~= t;
24 		}
25 	}
26 
27 	void add(T[] t) {
28 		synchronized (this) {
29 			array.assumeSafeAppend ~= t;
30 		}
31 	}
32 
33 	T pop() {
34 		synchronized (this) {
35 			if (array.length == 0)
36 				return T.init;
37 			T obj = array[$ - 1];
38 			array = array.remove(array.length - 1);
39 			return obj;
40 		}
41 	}
42 
43 }
44 
45 class LockedVector(T) {
46 	Vector!T array;
47 public:
48 	this() {
49 		//array=Mallocator.instance.make!(Vector!T)(16);
50 	}
51 
52 	~this() {
53 		//Mallocator.instance.dispose(array);
54 	}
55 
56 	bool empty() {
57 		return (array.length == 0);
58 	}
59 
60 	void add(T t) {
61 		synchronized (this) {
62 			array ~= t;
63 		}
64 	}
65 
66 	void add(T[] t) {
67 		synchronized (this) {
68 			array ~= t;
69 		}
70 	}
71 
72 	void removeElement(T elem) {
73 		synchronized (this) {
74 			array.removeElement(elem);
75 		}
76 	}
77 
78 	T pop() {
79 		synchronized (this) {
80 			if (array.length == 0)
81 				return T.init;
82 			T obj = array[$ - 1];
83 			array.remove(array.length - 1);
84 			return obj;
85 		}
86 	}
87 
88 	auto opSlice() {
89 		return array[];
90 	}
91 
92 	//allocated by Mallocator.instance
93 	Vector!T vectorCopy() {
94 		synchronized (this) {
95 			Vector!T vec; //=Mallocator.instance.make!(Vector!T)(array.length);
96 			vec ~= array[];
97 			return vec;
98 		}
99 	}
100 
101 	Vector!T vectorCopyWithReset() {
102 		if (array.length == 0)
103 			return Vector!T();
104 		synchronized (this) {
105 			scope (exit)
106 				array.reset;
107 			return array.copy;
108 		}
109 	}
110 
111 }