Code Monkey home page Code Monkey logo

littlebookofsemaphores's Introduction

LittleBookOfSemaphores

LaTeX source and supporting code for The Little Book of Semaphores, by Allen Downey.

To run the Sync thread simulator, make sure you have Python installed with tkinter.

Then

  1. Download this repository in a Zip file

  2. Unzip the zip file

unzip LittleBookOfSemaphores-master.zip
  1. Change into the directory that contains Sync.py
cd LittleBookOfSemaphores-master/code/
  1. Run Sync without example code:
python Sync.py
  1. Run Sync with example code:
python Sync.py sync_code/barrier.py 

If you are using Anaconda, you might find that the fonts don't look good. This is a well-known problem with no easy solution.

Translations

The following list of translations is sorted alphabetically.

If you have created a translation of this book and would like to add it to this list, feel free to submit a pull request or contact me to include it here.

littlebookofsemaphores's People

Contributors

allendowney avatar ghaseminya avatar javadr avatar quuxplusone avatar ramalho avatar stvhwrd avatar vavanade avatar yihangho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

littlebookofsemaphores's Issues

Add example code listed in the book's Web page to this repository

The book's Web page provides links to the source files listed below. None of them is in this repo, but they should be. There is a coke.py file in this repo at code/sync_code/coke.py but it is not the same coke.py linked from the book's page.

  • threading_cleanup.py
  • counter.py
  • counter_mutex.py
  • coke.py
  • counter.c
  • counter_mutex.c
  • semaphore.c

I'm not sending a pull request to add the files because I'm not sure where you'd like to put them.

I opened this issue because I wanted to make a pull request fixing threading_cleanup.py to run on Python 3, but I couldn't because that file is not in this repo.

Multi-Phase reusable Barrier class

Reusable Barrier class that can be used for any number of phases.
Uses two preloaded turnstiles and alternates between them upon completing another phase.

import sys
from threading import Thread, Semaphore


class Barrier:
    def __init__(self, num_threads):
        self.num_threads = num_threads
        self.count = 0
        self.mutex = Semaphore(1)
        self.turnstiles = (Semaphore(0), Semaphore(0))
        self.t = 0 # current active turnstile index

    def wait(self):
        # current active turnstile
        turnstile = self.turnstiles[self.t]

        self.mutex.acquire()
        self.count += 1
        if self.count == self.num_threads:
            # reset the counter to always count up, thus no difference between phase 1 and 2
            self.count = 0
            # alternate active turnstile
            self.t = 1 - self.t
            # wake threads with preloaded turnstile
            for _ in range(self.num_threads):
                turnstile.release()
        self.mutex.release()

        turnstile.acquire()


NUM_THREADS = 5
BARRIER = Barrier(NUM_THREADS)


def run(n):
    num_cycles = 3
    for i in range(num_cycles):
        sys.stdout.write('cycle {}: before {}\n'.format(i, n))
        BARRIER.wait()
        sys.stdout.write('cycle {}: between {}\n'.format(i, n))
        BARRIER.wait()
        sys.stdout.write('cycle {}: after {}\n'.format(i, n))
        BARRIER.wait()


THREADS = [Thread(target=run, args=(i,)) for i in range(NUM_THREADS)]

for t in THREADS:
    t.start()

for t in THREADS:
    t.join()

Kindle or phone friendly version?

Hi! I am not too familiar with Latex... how can I generate a version of this book that I can use on my Kindle or in my phone? (If it helps, I use the Libby app)

Thank you!

Clarify the rules of the Sushi Bar problem

The sushi bar problem description doesn't clarify all the rules that the solution must comply with.
The rules can be inferred from the solutions, but they should be stated in advance.

For reference, here is the problem description as of version 2.2.1

Imagine a sushi bar with 5 seats. If you arrive while there is an empty seat, you can take
a seat immediately. But if you arrive when all 5 seats are full, that means that
all of them are dining together, and you will have to wait for the entire party
to leave before you sit down.

Scenario 1:

  1. Bar is filling up with customers #1-#5, all 5 seats are now taken
  2. Customer #6 arrives, sees bar is full, realizes he must wait for entire party to leave
  3. Customer #1, who was just seated and eating, leaves the bar
  4. Customer #7 arrives, sees only 4 seated customers and 1 empty sit, has no reason to think the 4 customers are dining together...
  • Question: can customer #7 sit down?
  • By looking at the solutions: no, customer #7 must wait (expressed by the must_wait variable). He somehow knows the 4 customers are a party, even though he never saw the 5 seats full in his own eyes. Perhaps customer #6 told him.

Scenario 2:

  1. Bar is filling up with customers #1-#5, all 5 seats are now taken
  2. Customer #1, who was just seated and eating, leaves the bar
  3. Customer #6 arrives, sees only 4 seated customers and 1 empty sit, has no reason to think the 4 customers are dining together...
  • Question: can customer #6 sit down?
  • By looking at the solutions: no, customer #6 must wait. He somehow knows the 4 remaining customers used to be 5 and are part of a party, even though no other customer has arrived to see all 5 seats full. Maybe there is a waiter telling him, or maybe there is a "bar is full" sign hanging.

A different interpretation of these rules will yield a different solution, and might lead to other questions such as "do we need to ensure no-starvation?"

Mutex acquired by a thread should be released by same thread

The followers queue solution in section 3.8.4 'Exclusive queue' quotes

Actually, in this case the follower never releases mutex; the leader does. We don’t
have to keep track of which thread has the mutex because we know that one of
them does, and either one of them can release it. In my solution it’s always the leader.

Isn't that an undefined behavior ?
The thread who locks the mutex should be the one who unlocks it

V and P meaning

Hi,

I am very much enjoying your book so far, I notice however you do mention in a footnote that V and P are not entirely meaningless if you speak dutch. I fail to see however why you do not mention their meanings? It would make sense to explain V means vrijgeven (release) and P means proberen (try). It would make for everyone who reads your book clear that V and P do have an excellent meaning vs not important at all. It would also be nice especially given you say Dijkstra realised a meaningless name is better than a misleading name. I highly doubt that was his reasoning here...

Greetings, and many thanks for the otherwise excellent book!

Reading count value outside of mutex in Barrier solution

The Barrier solution in 3.6.4 has a note towards the end:

It might seem dangerous to read the value of count outside the mutex. In
this case it is not a problem, but in general it is probably not a good idea.

I did not understand why it is not a problem in this case. If all the threads signal() the barrier, then none of them will wait(), right ?

"Queue"

The word "queue" is used a few times, especially in section 3.8, to describe threads waiting on a semaphore. "Queue" typically implies (in both CS jargon and in common language) FIFO ordering, but that isn't the case with semaphores, right? No particular thread is guaranteed to be unblocked at a particular time, so it's more like a pool than a queue. I suggest adding a comment somewhere to clarify.

"Context switch" used without being defined

Section 3.7.6 says

But one drawback is that it forces threads to go through sequentially, which may cause more context switching than necessary.

I think it would be a good idea to say a word or two about this, maybe in the introduction.

Similarly, section 3.3.2 has

This solution also works, although it is probably less efficient, since it might have to switch between A and B one time more than necessary.

Is that also about context switching? A little more explanation would be good here too.

Unclear problem in 'Reusable barrier problem #1'

The problem described in the Section 3.7.2 for the non-solution in 3.7.1 is

If the n − 1th thread is interrupted at this point, and then the nth thread
comes through the mutex, both threads will find that count==n and both
threads will signal the turnstile. In fact, it is even possible that all the threads
will signal the turnstile.

Isn't this also true for the working solution described in 3.6.4 ? The text under that head says

It might seem dangerous to read the value of count outside the mutex. In
this case it is not a problem
Isn't that the same problem described in section 3.7.2 ?
What would be the problem if all the threads signal but none of them is in wait yet ?

Missing variables in `Faneuil Hall problem hint`

In the Faneuil Hall problem hint, it appears that two variables have been omitted. Let's introduce these variables in a more formal manner to maintain consistency with the existing text. After that, we will incorporate the additional notes within the main passage:

judge = 0
allSignedIn = Semaphore(0)

Including these variables, the complete code snippet will look as follows:

noJudge = Semaphore(1)
entered = 0
checked = 0
judge = 0
mutex = Semaphore(1)
confirmed = Semaphore(0)
allSignedIn = Semaphore(0)

Now, let's incorporate the additional notes:

judge shows whether the judge is entered or not.
allSignedIn represents that the certificates of all immigrants have been signed.

Concurrent Updates 1.5.2 Clarification Suggestion

Hi -

First off, thanks for making this fun book available!

In section 1.5.2 Concurrent updates, the thread of execution at machine level is shown with two steps:

1. temp = count
2. count = temp + 1

This is true for CISC processors that can operate directly on memory, but RISC processors I've worked with would break it down into three instructions, which together are called a read-modify-write operation.

So, Thread A would be

1. temp = count
2. temp = temp + 1
3. count = temp

which gives one more opportunity for another thread to slice in.

Cheers,

Jeff B.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.