From eab3cf03e5c7ea92c7a0fa90ae769bb38dec2d51 Mon Sep 17 00:00:00 2001 From: Jane Petrovna Date: Tue, 28 Dec 2021 20:53:30 -0500 Subject: [PATCH] mutex --- src/main.rs | 12 ++++++++---- src/util/webserver.rs | 16 +++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index d271e61..4ec9b25 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ pub mod util; use util::lights::*; use util::pattern::*; use util::webserver::*; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, RwLock, Mutex}; use rs_ws281x::{RawColor, Controller, ControllerBuilder, ChannelBuilder, StripType}; use std::{thread, time}; @@ -14,7 +14,7 @@ pub const LOOP_WAIT: u64 = 250; fn main() { let p: RawColor = [0, 0, 0, 0]; let lock = Arc::new(RwLock::new([p; LED_SIZE])); - let mut pattern: Vec> = Vec::new(); + let mut pattern: Arc>>> = Arc::new(Mutex::new(Vec::new())); let read = Arc::clone(&lock); //light management thread::spawn(move || { @@ -34,14 +34,18 @@ fn main() { } }); - websocket(&mut pattern); + let pat_clone = Arc::clone(&pattern); + thread::spawn(move || loop { + websocket(&pat_clone); + }); //pattern management loop { thread::sleep(time::Duration::from_millis(LOOP_WAIT)); let c_lock = Arc::clone(&lock); let mut lights = c_lock.write().unwrap(); - for p in &pattern { + let mut data = pattern.lock().unwrap(); + for p in *pattern { //let c_lock = Arc::clone(&lock); //let mut lights = c_lock.write().unwrap(); p.execute(&mut lights); diff --git a/src/util/webserver.rs b/src/util/webserver.rs index d5ba5b5..86d74fa 100644 --- a/src/util/webserver.rs +++ b/src/util/webserver.rs @@ -1,21 +1,23 @@ use std::net::TcpListener; -use std::thread; +use std::{thread, sync::{Arc, Mutex}}; use tungstenite::accept; -use crate::util::pattern; +use crate::util::pattern::*; -pub fn websocket(pattern: &mut Vec>) { +pub fn websocket(pattern: &Arc>>>) { let server = TcpListener::bind("0.0.0.0:29999").unwrap(); for stream in server.incoming() { + let clone = Arc::clone(pattern); thread::spawn (move || { let mut websocket = accept(stream.unwrap()).unwrap(); loop { let input = websocket.read_message().unwrap(); if input.is_text() { let string = input.to_text().unwrap_or("unit"); - let mul_string = pattern::format_multiline(string); - match mul_string.iter().cloned().map(pattern::parse_line).collect() { - Ok(patterns) => { - *pattern = patterns; + let mul_string = format_multiline(string); + match mul_string.iter().cloned().map(parse_line).collect() { + Ok(patterns) => { + let mut data = clone.lock().unwrap(); + *data = patterns; let text = format!("Ok!\n\n{}", string); let msg = tungstenite::Message::from(text); websocket.write_message(msg).unwrap();