Types of concurrency
- Shared memory
- Machine language primitives (e.g., Test-And-Set, Compare-And-Swap)
- Semaphores
- Monitors / Locks & condition variables
- Transactional memory
- Message passing
- MPI library
- Remote procedure calls / remote method invocation
- Actor model
- Data parallelism
- Parallel
for
loop
- MapReduce
Basic example: Harmonic number
import std.conv : to;
import std.stdio;
import std.string : strip;
void main() {
write("How many terms? ");
string input = readln();
if (input == null) return;
int terms = to!int(strip(input));
writeln(terms, "th harmonic number is ", harmonic(terms));
}
double harmonic(int n) {
double sum = 0.0;
foreach (i; 1 .. n + 1) {
sum += 1.0 / i;
}
return sum;
}
Arrays: Most frequent words
import std.algorithm : sort;
import std.array : array, splitter;
import std.stdio : stdin, writefln;
import std.string : strip, toLower;
void main() {
uint[string] freqs;
foreach (line; stdin.byLine) {
foreach (word; splitter(strip(line))) {
++freqs[toLower(word).idup];
}
}
auto words = array(freqs.keys);
auto compareFunc = (string a, string b) {
return freqs[a] > freqs[b] || freqs[a] == freqs[b] && a < b;
};
sort!compareFunc(words);
foreach (key; words[0..20]) {
writefln("%6u %s", freqs[key], key);
}
}
Classes: Average scores
import std.array : split;
import std.conv : to;
import std.stdio : stdin, writefln;
import std.string : strip;
void main() {
Student[string] students;
foreach (line; stdin.byLine()) {
auto tokens = split(strip(line), "\t");
int grade = to!int(tokens[0]);
string name = tokens[1].idup;
if (name in students) {
students[name].addScore(grade);
} else {
students[name] = new Student(grade);
}
}
foreach (name, student; students) {
writefln("%5.2f %s", student.getAverage(), name);
}
}
class Student {
private int total;
private int count;
this(int initScore) {
total = initScore;
count = 1;
}
void addScore(int score) {
total += score;
count++;
}
double getAverage() {
return cast(double) total / count;
}
}