Przeglądaj źródła

Everything working except from deserialization.

Joshua Rutschmann 7 lat temu
rodzic
commit
e7215e33da

+ 0
- 4
hw10/task1/Cargo.toml Wyświetl plik

@@ -4,11 +4,7 @@ version = "0.2.0"
4 4
 authors = ["Joshua Rutschmann <joshua.rutschmann@gmx.de>", "Lorenz Bung <lorenz.bung@htwg-konstanz.de>"]
5 5
 
6 6
 [dependencies]
7
-srv-commands = { path = "srv-commands" }
8 7
 srv-config = { path = "srv-config" }
9 8
 srv-hasher = { path = "srv-hasher" }
10
-serde = "1.0.27"
11
-serde_derive = "1"
12
-serde_json = "1"
13 9
 
14 10
 [workspace]

+ 96
- 111
hw10/task1/src/main.rs Wyświetl plik

@@ -1,83 +1,22 @@
1
-extern crate srv_commands;
2 1
 extern crate srv_config;
3 2
 extern crate srv_hasher;
4 3
 
5
-#[macro_use]
6
-extern crate serde_derive;
7
-extern crate serde;
8
-extern crate serde_json;
9
-
10
-use std::io::{BufReader, BufRead, BufWriter, Write};
11
-use std::collections::VecDeque;
4
+use std::io::{BufReader, BufRead, Write};
12 5
 use std::net::{TcpListener, TcpStream};
13
-use srv_commands::Command;
6
+use std::sync::atomic::{AtomicUsize, Ordering};
14 7
 use srv_config::Config;
15 8
 use srv_hasher::Solution;
16 9
 use std::{process, io, thread};
17 10
 use std::sync::Arc;
18
-use std::sync::Mutex;
19
-
20
-//#[derive(Serialize, Deserialize)]
21
-#[derive(Clone, Debug)]
22
-struct OrderQueue<T: Send + Copy> {
23
-    inner: Arc<Mutex<VecDeque<T>>>,
24
-}
25
-
26
-impl<T: Send + Copy> OrderQueue<T> {
27
-
28
-    fn new() -> Self {
29
-        Self { inner: Arc::new(Mutex::new(VecDeque::new())) }
30
-    }
31
-
32
-    fn deserialize() {
33
-        
34
-    }
35
-
36
-    fn serialize(&self) {
37
-        let inner_queue = self.inner.lock();
38
-        if let Ok(mut queue) = inner_queue {
39
-        }
40
-    }
41
-    
42
-    fn get_latest_order(&self) -> Option<T> {
43
-        let inner_queue = self.inner.lock();
44
-        if let Ok(mut queue) = inner_queue {
45
-            queue.pop_front()
46
-        } else {
47
-            panic!("MutexError");
48
-        }
49
-    }
50
-
51
-    fn add_order(&self, order: T) {
52
-        if let Ok(mut queue) = self.inner.lock() {
53
-            queue.push_front(order);
54
-        } else {
55
-            panic!("MutexError");
56
-        }
57
-    }
58
-}
11
+use srv_hasher::ParallelQueue;
59 12
 
60 13
 #[derive(Debug)]
61 14
 pub enum HashServerError {
62
-    Parse(srv_commands::ParseError),
63 15
     Io(std::io::Error),
64 16
 }
65 17
 
66
-impl From<std::io::Error> for HashServerError {
67
-    fn from(err: std::io::Error) -> HashServerError {
68
-        HashServerError::Io(err)
69
-    }
70
-}
71
-
72
-impl From<srv_commands::ParseError> for HashServerError {
73
-    fn from(err: srv_commands::ParseError) -> HashServerError {
74
-        HashServerError::Parse(err)
75
-    }
76
-}
77
-
78
-fn handle_client(stream: &TcpStream, orders:OrderQueue<&str>) {
18
+fn handle_client(stream: &TcpStream, orders:ParallelQueue<String>) {
79 19
     let mut reader = BufReader::new(stream);
80
-    let mut writer = BufWriter::new(stream);
81 20
 
82 21
     loop {
83 22
         let mut line = String::new();
@@ -86,23 +25,7 @@ fn handle_client(stream: &TcpStream, orders:OrderQueue<&str>) {
86 25
                 if n == 0 {
87 26
                     break;
88 27
                 }
89
-
90
-                let mut words = line.split_whitespace();
91
-                match words.next() {
92
-                    Some(difficulty) => {
93
-
94
-                        if let Some(range) = words.next() {
95
-                        }
96
-
97
-                        if let Some(port) = words.next() {
98
-                        }
99
-                        
100
-                        orders.add_order("Hello");
101
-                    },
102
-                    None => {},
103
-                }
104
-
105
-                let _ = writer.flush();
28
+                orders.add(line.trim_right().to_string());
106 29
             }
107 30
             _ => {
108 31
                 break;
@@ -127,29 +50,19 @@ pub fn main() {
127 50
 
128 51
     let host = format!("{}:{}", c.address, c.port);
129 52
 
130
-    let orders: OrderQueue<&str> = OrderQueue::new();
131
-    let mut results: VecDeque<Solution> = VecDeque::new();
132
-
133
-    let ord = orders.clone();
134
-
53
+    let orders: ParallelQueue<String> = ParallelQueue::new();
54
+	
55
+	let orders_1 = orders.clone();
56
+	
135 57
     thread::spawn(move || {
136 58
         match TcpListener::bind(host).map_err(HashServerError::Io) {
137 59
             Ok(listener) => {
138 60
                 for s in listener.incoming() {
139 61
                     if let Ok(stream) = s {
140
-                        if c.verbosity > 1 {
141
-                            println!("[DEBUG] New Client connected");
142
-                        }                       
143
-                        
144
-                        let order_queue = orders.clone();
145
-                        
62
+                        let order_queue = orders_1.clone();
146 63
                         thread::spawn(move || {
147 64
                             handle_client(&stream, order_queue);
148 65
                         });
149
-
150
-                        if c.verbosity > 1 {
151
-                            println!("[DEBUG] Client diconnected")
152
-                        }
153 66
                     }
154 67
                 }
155 68
             },
@@ -159,15 +72,81 @@ pub fn main() {
159 72
         }
160 73
     
161 74
     });
162
-
163
-    let stdin = io::stdin();
164
-    let mut sl = stdin.lock();
165
-    let stdout = io::stdout();
166
-    let mut ol = stdout.lock();
167 75
     
76
+	let threads_arc = Arc::new(AtomicUsize::new(5));
77
+	
78
+	let orders_2 = orders.clone();
79
+	
80
+	let threads = threads_arc.clone();
81
+	thread::spawn(move || {
82
+		loop {
83
+			if let Some(order) = orders_2.pop() {
84
+				let mut words = order.split(',');
85
+				let t = threads.load(Ordering::SeqCst);
86
+				
87
+				match (words.next(),words.next(),words.next()){
88
+					(Some(difficulty), None, None) => {
89
+						println!("\nSearching with {} threads for hash with difficulty: {}", t, difficulty);
90
+						prompt();
91
+						if let Some(sol) = srv_hasher::search_with_threads(t, difficulty.to_string(), 42, <usize>::max_value(), Some(1), true) {
92
+							println!("\nFound solution {:?}", sol);
93
+							prompt();
94
+						}
95
+					},
96
+					(Some(difficulty), Some(range), None) => {
97
+						if let Ok(rng) = range.parse::<usize>() {
98
+							println!("\nSearching with {} threads for hash with difficulty ({}) in range 0 - {} ", t, difficulty, range);
99
+							prompt();
100
+							let result_queue = srv_hasher::search_multiple_with_threads(t, difficulty.to_string(), 42, rng);
101
+							println!();
102
+							while let Some(solution) = result_queue.pop() {
103
+								println!("{:?}", solution);
104
+							}
105
+						}
106
+					},
107
+					(Some(difficulty), Some(range), Some(port)) => {
108
+						if let Ok(rng) = range.parse::<usize>() {
109
+							println!("\nSearching with {} threads for hash with difficulty ({}) in range 0 - {} ", t, difficulty, range);
110
+							prompt();
111
+
112
+							let result_queue = srv_hasher::search_multiple_with_threads(t, difficulty.to_string(), 42, rng);
113
+							let host = format!("{}:{}", c.address, port);
114
+							thread::spawn(move || {
115
+								match TcpListener::bind(host) {
116
+									Ok(listener) => {
117
+										for s in listener.incoming() {
118
+											if let Ok(mut stream) = s {
119
+												while let Some(solution) = result_queue.pop() {
120
+													stream.write(format!("{:?}\n", solution).as_bytes());
121
+													stream.flush();
122
+												}
123
+												
124
+											}
125
+										}
126
+									},
127
+									Err(e) => {
128
+										println!("Failed to start the MultiHashServer: {:?}", e);
129
+									}
130
+								}
131
+							});
132
+						}
133
+					},
134
+					(_, _, _) => {
135
+					
136
+					}
137
+				}
138
+			}
139
+		}
140
+	});
141
+	
142
+	
143
+	let orders_3 = orders.clone();
144
+	
145
+	let stdin = io::stdin();
146
+    let mut sl = stdin.lock();
147
+	
168 148
     loop {
169
-        ol.write(b"HashServer> ");
170
-        ol.flush();
149
+		prompt();
171 150
         let mut line = String::new();
172 151
         match sl.read_line(&mut line) {
173 152
             Ok(_) => {
@@ -177,18 +156,19 @@ pub fn main() {
177 156
                     Some("halt") => {
178 157
                         println!("Saving state...");
179 158
                         //Serialize here
159
+                        orders_3.serialize();
180 160
                         process::exit(0);
181 161
                     },
182
-                    Some("get") => {
183
-                        ord.serialize();
184
-                        println!("{:?}", ord);
185
-                    },
186 162
                     Some("continue") => {
187
-                        println!("Restoring state")
163
+                        println!("Restoring state");
164
+                        //orders.deserialize();
188 165
                     },
189 166
                     Some("threads") => {
190
-                        if let Some(thr) = lines.next() {
191
-                            println!("Setting thread count to {}", thr);
167
+                        if let Some(thread_string) = lines.next() {
168
+							if let Ok(thr) = thread_string.parse::<usize>() {
169
+								println!("Setting thread count to {}", thr);
170
+								threads_arc.store(thr, Ordering::SeqCst);
171
+							}
192 172
                         }
193 173
                     },
194 174
                     Some(&_) => {},
@@ -199,3 +179,8 @@ pub fn main() {
199 179
         }
200 180
     }
201 181
 }
182
+
183
+fn prompt(){
184
+	print!("HashServer> ");
185
+	io::stdout().flush().ok().expect("Could not flush stdout");
186
+}

+ 0
- 8
hw10/task1/srv-commands/Cargo.toml Wyświetl plik

@@ -1,8 +0,0 @@
1
-[package]
2
-name = "srv-commands"
3
-version = "0.1.0"
4
-authors = ["Joshua Rutschmann <joshua.rutschmann@gmx.de>"]
5
-
6
-[dependencies]
7
-sha2 = "0.7.0"
8
-time = "0.1"

+ 0
- 39
hw10/task1/srv-commands/src/lib.rs Wyświetl plik

@@ -1,39 +0,0 @@
1
-pub fn parse(message: &str) -> Result<Command, ParseError> {
2
-    let m: String = String::from(message.trim_right());
3
-    let mut line = m.lines();
4
-    match line.next() {
5
-        Some(x) => {
6
-            let mut str = x.split_whitespace();
7
-            match str.next() {
8
-                Some("STAGE") => {
9
-                    let msg = m[6..].trim_left();
10
-                    Ok(Command::Stage(msg.to_string()))
11
-                }
12
-                Some("CONTROL") => {
13
-                    let cmd = m[8..].trim_left();
14
-                    Ok(Command::Control(cmd.to_string()))
15
-                }
16
-                Some("RETRIEVE") => Ok(Command::Retrieve),
17
-                Some(_) => Err(ParseError(ErrorType::UnknownCommand)),
18
-                None => Err(ParseError(ErrorType::EmptyString)),
19
-            }
20
-        }
21
-        None => Err(ParseError(ErrorType::EmptyString)),
22
-    }
23
-}
24
-
25
-#[derive(Debug, PartialEq)]
26
-pub enum Command {
27
-    Stage(String),
28
-    Control(String),
29
-    Retrieve,
30
-}
31
-
32
-#[derive(Debug, PartialEq)]
33
-pub struct ParseError(pub ErrorType);
34
-
35
-#[derive(Debug, PartialEq)]
36
-pub enum ErrorType {
37
-    UnknownCommand,
38
-    EmptyString,
39
-}

+ 0
- 43
hw10/task1/srv-commands/tests/srv-commands.rs Wyświetl plik

@@ -1,43 +0,0 @@
1
-#[cfg(test)]
2
-
3
-mod tests {
4
-	extern crate srv_commands;
5
-    use self::srv_commands::*;
6
-
7
-    #[test]
8
-    fn empty_returns_correct_command() {
9
-        assert_eq!(parse("\n"), Err(ParseError(ErrorType::EmptyString)))
10
-    }
11
-
12
-    #[test]
13
-    fn not_known_command_returns_correct_command() {
14
-        assert_eq!(parse("Hello\n"), Err(ParseError(ErrorType::UnknownCommand)))
15
-    }
16
-
17
-    #[test]
18
-    fn stage_returns_correct_command() {
19
-        assert_eq!(
20
-            parse("STAGE Hello\n"),
21
-            Ok(Command::Stage("Hello".to_string()))
22
-        )
23
-    }
24
-
25
-    #[test]
26
-    fn control_returns_correct_command() {
27
-        assert_eq!(
28
-            parse("CONTROL Hello\n"),
29
-            Ok(Command::Control("Hello".to_string()))
30
-        )
31
-    }
32
-
33
-    #[test]
34
-    fn retrieve_returns_correct_command() {
35
-        assert_eq!(parse("RETRIEVE\n"), Ok(Command::Retrieve))
36
-    }
37
-
38
-    #[test]
39
-    fn retrieve_with_arguments_returns_correct_command() {
40
-        assert_eq!(parse("RETRIEVE Hello\n"), Ok(Command::Retrieve))
41
-    }
42
-
43
-}

+ 3
- 1
hw10/task1/srv-hasher/Cargo.toml Wyświetl plik

@@ -5,4 +5,6 @@ authors = ["Joshua Rutschmann <joshua.rutschmann@gmx.de>"]
5 5
 
6 6
 [dependencies]
7 7
 sha2 = "0.7.0"
8
-time = "0.1"
8
+serde = "1.0.27"
9
+serde_derive = "1"
10
+serde_json = "1"

+ 154
- 72
hw10/task1/srv-hasher/src/lib.rs Wyświetl plik

@@ -1,14 +1,73 @@
1 1
 extern crate sha2;
2
-extern crate time;
2
+
3
+#[macro_use]
4
+extern crate serde_derive;
5
+extern crate serde;
6
+extern crate serde_json;
3 7
 
4 8
 #[cfg(feature = "SHA2")]
5 9
 use self::sha2::Sha256;
6 10
 use std::thread;
7
-use std::sync::Arc;
11
+use std::sync::{Arc, Mutex};
12
+use std::collections::VecDeque;
8 13
 use std::sync::atomic::AtomicBool;
9 14
 use std::sync::atomic::Ordering::Relaxed;
10 15
 use std::sync::mpsc::{Sender, channel};
11
-use time::{Duration, get_time};
16
+use std::fs::File;
17
+use std::io::Write;
18
+use std::ops::Deref;
19
+
20
+#[derive(Serialize)]
21
+struct InnerQueue<T> {
22
+	inner: VecDeque<T>,
23
+}
24
+
25
+impl<'a, T: Send + Clone + serde::Serialize> InnerQueue<T> {
26
+
27
+    fn new() -> Self {
28
+        Self { inner: VecDeque::new() }
29
+    }
30
+	
31
+}
32
+
33
+#[derive(Clone)]
34
+pub struct ParallelQueue<T> {
35
+    inner: Arc<Mutex<InnerQueue<T>>>,
36
+}
37
+
38
+impl<'a, T: Send + Clone + serde::Serialize> ParallelQueue<T> {
39
+
40
+    pub fn new() -> Self {
41
+        Self { inner: Arc::new(Mutex::new(InnerQueue::new())) }
42
+    }
43
+
44
+    pub fn serialize(&self) {
45
+        let inner_queue = self.inner.lock();
46
+        if let Ok(queue) = inner_queue {
47
+            let queue_json = serde_json::to_string(queue.deref()).unwrap();
48
+            let mut file = File::create("orders.save").unwrap();
49
+            file.write_all(queue_json.as_bytes());
50
+        }
51
+    }
52
+    
53
+    pub fn pop(&self) -> Option<T> {
54
+        let inner_queue = self.inner.lock();
55
+        if let Ok(mut queue) = inner_queue {
56
+            queue.inner.pop_front()
57
+        } else {
58
+            panic!("MutexError");
59
+        }
60
+    }
61
+	
62
+    pub fn add(&self, order: T) {
63
+        if let Ok(mut queue) = self.inner.lock() {
64
+            queue.inner.push_back(order);
65
+        } else {
66
+            panic!("MutexError");
67
+        }
68
+    }
69
+}
70
+
12 71
 
13 72
 
14 73
 pub struct Sha256;
@@ -103,7 +162,7 @@ impl HashResult for [u8; 32] {
103 162
     }
104 163
 }
105 164
 
106
-#[derive(Debug, PartialEq)]
165
+#[derive(Debug, PartialEq, Clone, Serialize)]
107 166
 pub struct Solution {
108 167
     pub number: usize,
109 168
     pub hash: String,
@@ -137,19 +196,16 @@ fn search_hash(
137 196
     hash: &String,
138 197
     base: usize,
139 198
     start: usize,
199
+	end: usize,
140 200
     total: usize,
141 201
     sync: bool,
142 202
     found: Arc<AtomicBool>,
143 203
     special: usize,
144 204
     solution_tx: Sender<Solution>,
145
-    timing_tx: Sender<(Duration, usize)>,
146
-    measure: bool,
147 205
 ) {
148
-    let max = <usize>::max_value();
149 206
     let mut n = start;
150 207
 
151
-    let thread_start = get_time();
152
-    while n < max {
208
+    while n < end {
153 209
 
154 210
         // Der special Parameter begrenzt die Anzahl der load()-Aufrufe auf jeden n.ten Loop.
155 211
         if n % special == 0 && found.load(Relaxed) {
@@ -168,12 +224,6 @@ fn search_hash(
168 224
         }
169 225
         n += total;
170 226
     }
171
-
172
-    // Falls measure aktiviert ist Sende Zeitdauer und Anzahl Loops an den Consumer.
173
-    if measure {
174
-        let thread_end = get_time();
175
-        let _ = timing_tx.send((thread_end - thread_start, (n / total)));
176
-    }
177 227
 }
178 228
 
179 229
 /// Teilt, wenn nötig, die Suche nach dem Hash auf mehrere Threads auf.
@@ -182,35 +232,25 @@ pub fn search_with_threads(
182 232
     threads: usize,
183 233
     diff_string: String,
184 234
     with_base: usize,
185
-    time_measurement: bool,
186
-    verbosity: u64,
235
+	range_of_numbers: usize,
187 236
     sync: Option<usize>,
188 237
     wait: bool,
189
-) -> Option<Solution> {
190
-
238
+) -> Option<Solution> {	
191 239
     let diff = Arc::new(diff_string);
192 240
     let mut children = vec![];
193 241
     let mut solution = None;
194 242
 
195
-    let (solution_tx, solution_rx) = channel();
196
-    let (timing_tx, timing_rx) = channel();
197
-
243
+	let (solution_tx, solution_rx) = channel();
244
+	
198 245
     let found = Arc::new(AtomicBool::new(false));
199
-    let m = time_measurement && verbosity > 0;
200 246
 
201
-    let total_start = get_time();
202 247
     if threads > 1 {
203 248
 
204
-        if verbosity > 0 {
205
-            println!("Searching with {} threads", threads);
206
-        }
207
-
208 249
         // Erstellt Anzahl angeforderter Threads.
209 250
         // Klont für jeden Thread die Referenz auf die gemeinsamen Variablen.
210 251
         for i in 0..threads {
211 252
             let diff = diff.clone();
212 253
             let solution_tx = solution_tx.clone();
213
-            let timing_tx = timing_tx.clone();
214 254
             let found = found.clone();
215 255
 
216 256
             children.push(thread::spawn(move || {
@@ -220,18 +260,14 @@ pub fn search_with_threads(
220 260
                     &diff,
221 261
                     with_base,
222 262
                     i,
263
+					range_of_numbers,
223 264
                     threads,
224 265
                     sync.is_some(),
225 266
                     found,
226 267
                     sync.unwrap_or(1),
227 268
                     solution_tx,
228
-                    timing_tx,
229
-                    m,
230 269
                 );
231 270
 
232
-                if verbosity > 1 {
233
-                    println!("[DEBUG] Thread {} exited", i);
234
-                }
235 271
             }));
236 272
         }
237 273
     } else {
@@ -240,70 +276,116 @@ pub fn search_with_threads(
240 276
             &diff,
241 277
             with_base,
242 278
             0,
279
+			range_of_numbers,
243 280
             1,
244 281
             sync.is_some(),
245 282
             found,
246 283
             sync.unwrap_or(1),
247 284
             solution_tx,
248
-            timing_tx,
249
-            m,
250 285
         );
251 286
 
252
-        if verbosity > 1 {
253
-            println!("[DEBUG] Finished search on main thread.");
254
-        }
255 287
     }
256
-
257
-    // Empfängt die Lösung von einem der Producer.
288
+	
289
+	// Empfängt die Lösung von einem der Producer.
258 290
     match solution_rx.recv() {
259 291
         Ok(sol) => {
260 292
             solution = Some(Solution {
261 293
                 number: sol.number,
262 294
                 hash: sol.hash.clone(),
263 295
             });
264
-            let total_end = get_time();
265
-            println!("Number: {} --> hash: {}", sol.number, sol.hash);
266
-            if time_measurement && verbosity == 0 {
267
-                let diff = total_end - total_start;
268
-                let s = diff.num_seconds();
269
-                let ms = diff.num_milliseconds();
270
-                let us = diff.num_microseconds().unwrap_or(ms * 1000);
271
-                println!("(Duration {}s / {}ms / {}us)", s, ms, us);
272
-            }
273 296
         }
274 297
         Err(_) => {}
275 298
     }
276 299
 
277
-    let mut sum_loops = 0usize;
278
-    let mut sum_time: Duration = Duration::zero();
279
-
280 300
     for child in children {
281
-
282
-        if time_measurement && verbosity > 0 {
283
-            // Warte auf Zeitstatistik-Nachricht von jedem Thread auf dem zweiten MPSC Channel.
284
-            if let Ok(stats) = timing_rx.recv() {
285
-                // Addiere Werte dieses threads zu der Summe.
286
-                sum_time = sum_time + stats.0;
287
-                sum_loops += stats.1;
288
-            }
289
-        }
290
-
291 301
         // Falls *wait* wahr ist, warte auf aktuellen thread (child)
292 302
         if wait {
293 303
             let _ = child.join();
294 304
         }
295 305
     }
296 306
 
297
-    // Gebe die Gesamtergebnisse der Threads aus.
298
-    if time_measurement && verbosity > 0 {
299
-        println!("Sum Loops in Producers:       {}", sum_loops);
300
-        let s = sum_time.num_seconds();
301
-        let ms = sum_time.num_milliseconds();
302
-        let us = sum_time.num_microseconds().unwrap_or(ms * 1000);
303
-        println!("Sum Duration in Producers:    {}s / {}ms / {}us", s, ms, us);
304
-    }
305
-
306 307
     // Gebe die Option einer Solution zurück.
307 308
     solution
308 309
 }
309 310
 
311
+
312
+
313
+/// Sucht nach einem Hash für die angegebene Basis und die Schwierigkeit.
314
+/// Wenn `total` > 1 ist, dann hat jeder Aufruf mit einem anderen `start`-Wert (von 0 - total)
315
+/// eine disjunkte Zahlenmenge für die Suche zur Auswahl.
316
+fn search_multiple_hash(
317
+    hash: &String,
318
+    base: usize,
319
+    start: usize,
320
+	end: usize,
321
+    total: usize,
322
+	queue: ParallelQueue<Solution>,
323
+) {
324
+    let mut n = start;
325
+
326
+    while n < end {
327
+        if let Some(solution) = verify_product(base, n, hash) {
328
+
329
+            // Sende gefundene Solution an den Consumer.
330
+			queue.add(solution);
331
+            break;
332
+        }
333
+        n += total;
334
+    }
335
+}
336
+
337
+/// Teilt, wenn nötig, die Suche nach dem Hash auf mehrere Threads auf.
338
+/// Gibt ggf. die Solution (für die Tests) zurück.
339
+pub fn search_multiple_with_threads(
340
+    threads: usize,
341
+    diff_string: String,
342
+    with_base: usize,
343
+	range_of_numbers: usize,
344
+) -> ParallelQueue<Solution> {	
345
+    let diff = Arc::new(diff_string);
346
+    let mut children = vec![];
347
+	let result_queue:ParallelQueue<Solution> = ParallelQueue::new();
348
+
349
+    if threads > 1 {
350
+
351
+        // Erstellt Anzahl angeforderter Threads.
352
+        // Klont für jeden Thread die Referenz auf die gemeinsamen Variablen.
353
+        for i in 0..threads {
354
+            let diff = diff.clone();
355
+			let queue = result_queue.clone();
356
+			
357
+            children.push(thread::spawn(move || {
358
+
359
+                // Suche in jedem der Threads.
360
+                search_multiple_hash(
361
+                    &diff,
362
+                    with_base,
363
+                    i,
364
+					range_of_numbers,
365
+                    threads,
366
+                    queue,
367
+                );
368
+
369
+            }));
370
+        }
371
+    } else {
372
+        // Suche auf dem Main-Thread.
373
+		let queue = result_queue.clone();
374
+        search_multiple_hash(
375
+            &diff,
376
+            with_base,
377
+            0,
378
+			range_of_numbers,
379
+            1,
380
+			queue,
381
+		);
382
+
383
+    }
384
+
385
+    for child in children {
386
+        let _ = child.join();
387
+    }
388
+	
389
+	result_queue
390
+}
391
+

Ładowanie…
Anuluj
Zapisz