concurrency

Coding Challenge Coding Live

Is it acceptable to ask for course notes ahead of time?

Learn more about hiring developers or posting ads with us

Why is moon light not the same color as sunlight?

Prime Number Rows in a Pascals Triangle

What kinds of weapons produce little or no recoil that could be used aboard a spacestation?

Unwrapping is undesirable. See if you can avoid it.get_coinscan be rewritten thus (note how this also makes it only one lookup rather than two, so its faster as well):

Closed balls vs closure of open balls

Stack Exchange network consists of 174 Q&A communities includingStack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Detailed answers to any questions you might have

TikZ and FIFA WorldCup 2018: Flags of Nations

How can I invite my daughters friends over without being odd?

I wrote this in 78 minutes as part of an application to an internship program. We were allowed to use whatever language we wanted, so I picked Rust because thats what I use the most. Im a Sophomore CS/Data Science major and I just wanted to get a feel for how you more experienced among us feel about what I made.

![feature(test)]shouldnt be necessary; you dont appear to be using any unstable features (mostly just benchmarking, really).

Does the C standard permit assigning an arbitrary value to a pointer and incrementing it?

if client guesses it, server raises their balance by 1 and picks new number

fn inc_balance(&mut self, user_id: String) // Credit the user for the correct guess, // inserting the user if not already in the database *self.balances.lock().unwrap().entry(user_id).or_insert(0) += 1;

//! XternCoin Application //! Casey Primozic – 2016 //! //! Requires latest Rust nightly // turn on the unstable testing feature ![feature(test)] extern crate rand; extern crate test; use std::sync::Arc, Mutex; use rand::thread_rng, Rng; use std::collections::HashMap; use std::sync::atomic::Ordering, AtomicUsize; use std::thread; use std::convert::From; /// The server which manages the Proof of Work check and dispenses the currency /// /// The server is threadsafe and can be duplicated over an arbitary number of threads /// so that any number of users can mine simultaneously. [derive(Clone)] struct CoinServer // concurrent hashmap to store the balances of all users // this allows shared mutable access to the balance database through `lock()`. pub balances: ArcMutexHashMapString, f64, // only public for sake of the test pub random_num: ArcAtomicUsize, impl CoinServer /// Function which takes a users id and a users guess, /// and returns whether or not their guess was correct. pub fn handle_guess(&mut self, user_id: String, guess: u64) // convert the String to a u64 for comparison if self.random_num.load(Ordering::Relaxed) == guess as usize c_balance(user_id); self.get_new_rand(); /// Adds one to the users balance, creating an entry for it if /// it doesnt exist. fn inc_balance(&mut self, user_id: String) // lock the balances let mut balances = self.balances.lock().unwrap(); // insert user if not already in database if ntains_key(&user_id) balances.insert(user_id, 1f64); return // credit the user for the correct guess let balance = balances.get_mut(&user_id).unwrap(); *balance += 1f64; /// Function which takes a userid and returns /// how many coins they have. pub fn get_coins(&mut self, user_id: String) – f64 let balances = self.balances.lock().unwrap(); if !balances.contains_key(&user_id) return 0f64 *balances.get(&user_id).unwrap() pub fn new() – CoinServer let mut server = CoinServer balances: Arc::new(Mutex::new(HashMap::new())), random_num: Arc::new(AtomicUsize::new(0)) ; server.get_new_rand(); server // Im using a text editor to debug this: /// Creates a new random number for users to try to guess fn get_new_rand(&mut self) // entropy source let mut rng = rand::thread_rng(); // generate random number from 0 to 100000 let rand_num: usize = rng.gen_range(0, 100000); self.random_num.store(rand_num, Ordering::Relaxed); /// A function which, when called, pretends to be a user of /// XternCoin and uses the other two functions youve written /// to accumulate coins by guessing random numbers in a loop fn start_guessing(user_id: String, mut server: CoinServer, iterations: usize) // entropy source let mut rng = rand::thread_rng(); for _ in 0..iterations let guess: u64 = rng.gen_range(0, 100000); // make guess and let server verify it server.handle_guess(user_id.clone(), guess); fn main() let server = CoinServer::new(); // spawn 10 threads to start guessing for i in 0..10 let mut server_clone = server.clone(); thread::spawn(move let user_id = format!(, i); // initiate mining start_guessing(user_id.clone(), server_clone.clone(), 100000); println!(Balance for after this mining session: , user_id.clone(), server_clone.get_coins(user_id)); ); // block so the miners can mine thread::park(); // TODO: tests1 /// Check to make sure that user balances are created and incremented [test] fn test_mining() let mut server = CoinServer balances: Arc::new(Mutex::new(HashMap::new())), random_num: Arc::new(AtomicUsize::new(42)) // cheat for the test ; let user_id = Test.to_string(); server.handle_guess(user_id.clone(), 42); // make sure we got credited assert_eq!(server.get_coins(user_id), 1f64); // server generated a new random number assert!(server.random_num.load(Ordering::Relaxed) != 42); // test passes:

site design / logo 2018 Stack Exchange Inc; user contributions licensed undercc by-sa 3.0withattribution required.rev2018.6.28.30907

(Note: at present this actually doesnt play optimally with using&strforuser_idas it requires you to clone the user ID every time you callinc_balancerather than only the first time a user ID is encountered.RFC PR 1769would fix that.)

Are there any conventions around closing an account with a credit balance?

Did Emmanuel Macron call a teenager an idiot?

Expressed simply: testing your own code shouldnt haveanyimpact on the API exposed to library users.

What time zone is used for operating an airplane?

How to make a 6 year old think more?

Why do many landscapers put rocks around the base of buildings?

The beauty of them is that theyre shorter, more efficient and clearer (after a short acclimation, anyway).

What did Grandpa eat for dessert?. Another Grandpa Mystery

Please copy and paste your output as

History behind the text column restriction

Start here for a quick overview of the site

use std::convert::From;is unnecessary (Fromis in the prelude).

Im not asking for detailed analysis (I know it works and that that it fits the prompt), Im just looking for broad feedback and any random observations.

This site uses cookies to deliver our services and to show you relevant ads and job listings. By using our site, you acknowledge that you have read and understand ourCookie PolicyPrivacy Policy, and ourTerms of Service. Your use of Stack Overflows Products and Services, including the Stack Overflow Network, is subject to these policies and terms.

[package] name = xt version = 0.1.0 authors = [Casey Primozic ] [dependencies] rand = 0.3

user_idshould be&strrather thanStringin most places. Basically, you should never need to clone theStringafter the first time when you insert it intobalances(to remedy that, you could useArcStringinstead if you wished; not sure if I would or not). Youre doing a lot more memory allocation than is necessary.

AtomicUsizeis alreadySync; no need to wrap it inArc.

How much difference does wind chill make if you are inside a snow cave?

Learn more about Stack Overflow the company

Something to bear in mind: youre locking theentirebalances table to make any changes at present. This is probably undesirable. If you were doing this seriously, youd be using a proper database which would take care of this stuff properly. Just thought Id mention it.

. Images are rarely the correct form to communicate programming information.

Thanks for the amazing feedback! Those two one-liners were really clever. I really appreciate the time you took to do this.

Making private fields public only for the sake of tests is undesirable; you should instead add new methods which are only available in tests, e.g.

Discuss the workings and policies of this site

How did Russia retain the UNSC veto power of the Soviet Union?

Why, until recently, were smooth nose sections not popular?

HashMap has some really nice things for efficiency. Just asgetreturned anOptionin the previous point (which rendered thecontains_keypart superfluous),inc_balancecan use theEntry APIto do less work:

Sign uporlog into customize your list.

By clicking Post Your Answer, you acknowledge that you have read our updatedterms of serviceprivacy policyandcookie policy, and that your continued use of the website is subject to these policies.

Leave a Reply