Threads

What a thread is and how it differs from a process, what threads share or do not, the pthread_create and pthread_join calls, and the race condition when two threads touch the same variable.

  • 27 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Thread: what is it?

    Show the answer

    A flow of execution inside a process: it has its own stack and registers, but shares the process's memory and open files with the others.

    Creating a thread costs less than a process and threads communicate without copying, but that shared access is the source of race conditions.

  • Two threads start from a counter at 0. Each does read, add, write. The order is: T1 reads, T2 reads, T1 writes, T2 writes. What is the counter at the end?

    • 1
    • 0
    • 2
    • 3
    Show the answer

    1

    T1 and T2 both read 0, add 1 and write 1: the second write overwrites the first. One update is lost, whereas with T1 complete then T2 complete you would get 2.

  • Each thread has its own …, but all threads of a process share the … and the global variables.

    Show the answer

    Each thread has its own stack, but all threads of a process share the heap and the global variables.

    Local variables live on the stack: each thread has its own. The heap and globals belong to the whole process.

  • Race condition: what is it?

    Show the answer

    A defect where the result depends on the order in which threads access a shared piece of data, at least one of them modifying it.

    It does not show on every run, which makes it hard to reproduce. Two threads each doing compteur++ 100,000 times, compiled without optimisation on a multi-core machine, almost always give less than 200,000.

  • Four threads are created in a loop with pthread_create(&t[i], NULL, f, &i). Each prints *arg and 4 4 4 4 is sometimes seen. What is the cause, and the fix?

    • The threads run one after another; add a pthread_join in the creation loop
    • pthread_create is too slow for the loop; create processes with fork instead
    • They all read the same i, already advanced; pass the address of a separate copy per thread
    • Each thread has its own stack, so i is copied on creation; declare i as static
    Show the answer

    They all read the same i, already advanced; pass the address of a separate copy per thread

    &i is the address of one of main's variables, shared by all. Each thread reads whatever value i holds at that moment, from 0 to 4 depending on how far the loop has gone. You need one slot per thread, such as int id[4] with &id[i], left unchanged afterwards. static changes nothing: still a single slot.