Skip to content

Instantly share code, notes, and snippets.

@stewart
Created December 14, 2016 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stewart/ef144452dcd008027cdf1959ea911e53 to your computer and use it in GitHub Desktop.
Save stewart/ef144452dcd008027cdf1959ea911e53 to your computer and use it in GitHub Desktop.
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)
}
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}"
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