25 Sep — D introduction

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 == nullreturn;
    int terms = to!int(strip(input));
    writeln(terms"th harmonic number is "harmonic(terms));
}

double harmonic(int n) {
    double sum = 0.0;
    foreach (i1 .. n + 1) {
        sum += 1.0 / i;
    }
    return sum;
}

Arrays: Most frequent words

import std.algorithm : sort;
import std.array : arraysplitter;
import std.stdio : stdinwritefln;
import std.string : striptoLower;

void main() {
    uint[stringfreqs;
    foreach (linestdin.byLine) {
        foreach (wordsplitter(strip(line))) {
            ++freqs[toLower(word).idup];
        }
    }

    auto words = array(freqs.keys);
    auto compareFunc = (string astring b) {
        return freqs[a] > freqs[b] || freqs[a] == freqs[b] && a < b;
    };
    sort!compareFunc(words);

    foreach (keywords[0..20]) {
        writefln("%6u %s"freqs[key], key);
    }
}

Classes: Average scores

import std.array : split;
import std.conv : to;
import std.stdio : stdinwritefln;
import std.string : strip;

void main() {
    Student[stringstudents;
    foreach (linestdin.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 (namestudentstudents) {
        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(doubletotal / count;
    }
}