Rust Programming 썸네일형 리스트형 [Rust] 7. Scoped threads, Channels scoped threads는 spawned thread가 parent를 outlive하는 issue를 회피하기 위한 방법이다. let v = vec![1, 2, 3];let midpoint = v.len() / 2;std::thread::scope(|scope| { scope.spawn(|| { let first = &v[..midpoint]; println!("Here's the first half of v: {first:?}"); }); scope.spawn(|| { let second = &v[midpoint..]; println!("Here's the second half of v: {second:?}"); });});prin.. 더보기 [Rust] 7. Leaking memory spawned thread에 references를 넘기는 것에가장 큰 문제가 use-after-free bugs다. use-after-free bugs는 이미 free됐거나 de-allocate된 memory영역을pointer를 통해 접근하는 것이다. 만약 heap에 할당된 data를 다룬다면,그 memory를 절대 회수하지 않을 것이라고 Rust에게 알려줌으로써,이 문제를 피할 수 있다.즉, 의도적으로 메모리 누수를 선택하는 것이다, Rust standard library의 Box::leak method를 통해 할 수 있다.// Allocate a `u32` on the heap, by wrapping it in a `Box`.let x = Box::new(41u32);// Tell Rust that .. 더보기 [Rust] 7. 'static lifetime 이전 exercise에서 vector를 둘로 나누지 않고borrow하려 했다면, 다음과 같은 compiler error가 뜰 것이다.error[E0597]: `v` does not live long enough |11 | pub fn sum(v: Vec) -> i32 { | - binding `v` declared here...15 | let right = &v[split_point..]; | ^ borrowed value does not live long enough16 | let left_handle = spawn(move || left.iter().sum::()); | -.. 더보기 [Rust] 7. Threads Chapter 7은 concurrent ticket management system을 위한 단원이다. 지금까지 본 것들은 single-threaded였을 때고, 이제는 그것을 바꿀 때다. 그래서 ticket store을 multithreaded로 바꿀 것이다. 그와 관련된 Rust의 중요한 concurrency features를 배울 것인데, 그것들은 다음과 같다. std::thread module을 사용한 Threads.channels를 사용한 Message passingArc, Mutex, RwLock을 사용한 공유 상태Rust의 concurrency guarantees를 encode한 traits인 Send와 Syncmultithreaded systems의 다양한 patterns와 trade-off.. 더보기 [Rust] 6. HashMap, BTreeMap 이전에 본 Index와 IndexMut는 이상적이지 않다.왜냐하면 id로 전체 Vec를 iterate해야하기 때문에,시간복잡도는 O(n)이다. 따라서 tickets를 저장하는 다른 자료구조를 사용할 것이다.그것이 HashMap다.use std::collections::HashMap;// Type inference lets us omit an explicit type signature (which// would be `HashMap` in this example).let mut book_reviews = HashMap::new();book_reviews.insert( "Adventures of Huckleberry Finn".to_string(), "My favorite book.".to_str.. 더보기 [Rust] 6. Index trait, IndexMut trait TicketStore에 Indexing을 추가하는 것을 할 것이다. Index trait을 implement하여 할 수 있는데, Index trait은 Rust의 standard library에 정의되어 있다.// Slightly simplifiedpub trait Index{ type Output; // Required method fn index(&self, index: Idx) -> &Self::Output;} index type을 나타내는 하나의 generic parameter Idx와index를 통해 반환받는 type을 나타내는 하나의 associated type Output이 있다.index method가 Option을 return하지 않는 방식에 이유가 궁금하면,array와 .. 더보기 [Rust] 6. Ticket Management: Slices, Mutable slices, Two states Vec의 memory layout을 보면 다음과 같다.let mut numbers = Vec::with_capacity(3);numbers.push(1);numbers.push(2); +---------+--------+----------+Stack | pointer | length | capacity | | | | 2 | 3 | +--|------+--------+----------+ | | v +---+---+---+Heap: | 1 | 2 | ? | +---+---+---+ 우리는 String이 Vec로 표현된다는 것을 언급했다.그럼 Vec에 대한 &str과 동일한 것은 무.. 더보기 [Rust] 6. Ticket Management: Combinators, impl Trait Iterators는 for loops보다 더 많은 것을 할 수 있다.만약 당신이 Iterator trait에 대한 documentation을 본다면,Iterators를 다양한 방법으로 transform하고 filter하고 combine하는methods의 많은 collections를 찾을 수 있을 것이다. 그 중 대중적인 것들을 이야기해보자. map은 iterator의 각 element에 function을 적용한다.filter는 조건을 만족하는 elements만 keep한다.filter_map은 filter와 map을 한번에 결합한다.cloned는 각 element를 clone하여, references의 iterator를 values의 iterator로 변환한다.enumerate는 (index, value.. 더보기 이전 1 2 3 4 다음