Created
December 14, 2016 01:09
-
-
Save stewart/ef144452dcd008027cdf1959ea911e53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
type Counter struct { | |
count int | |
} | |
func (c *Counter) increment() { | |
c.count += 1 | |
} | |
func main() { | |
counter := Counter{} | |
wait := sync.WaitGroup{} | |
counter.increment() | |
for i := 0; i < 3; i++ { | |
wait.Add(1) | |
go func() { | |
for x := 0; x < 1000000; x++ { | |
counter.increment() | |
} | |
wait.Done() | |
}() | |
} | |
wait.Wait() | |
fmt.Println("Count: ", counter.count) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Counter | |
attr_accessor :count | |
def initialize | |
@count = 0 | |
end | |
def increment | |
@count += 1 | |
end | |
end | |
counter = Counter.new | |
(0..3).map do | |
Thread.new do | |
1_000_000.times { counter.increment } | |
end | |
end.join | |
puts "Count: #{counter.count}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
struct Counter { | |
pub count: i32 | |
} | |
impl Counter { | |
pub fn new() -> Counter { | |
Counter { count: 0 } | |
} | |
pub fn increment(&mut self) { | |
self.count += 1; | |
} | |
} | |
fn main() { | |
let mut threads = vec![]; | |
let counter = Arc::new(Mutex::new(Counter::new())); | |
for _ in 0..3 { | |
let counter = counter.clone(); | |
let child = thread::spawn(move || { | |
let mut counter = counter.lock().unwrap(); | |
for _ in 0..1_000_000 { | |
counter.increment(); | |
} | |
}); | |
threads.push(child); | |
} | |
for thread in threads { | |
thread.join().unwrap(); | |
} | |
let counter = counter.clone(); | |
let counter = counter.lock().unwrap(); | |
println!("Count: {}", counter.count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment