CS202: HW 3: Concurrency practice

CS202: HW 3: Concurrency practice

These problems should be done on your own. You get credit if you turn in something, and we are not checking the correctness. So these exercises exist purely to reinforce the material, not to evaluate you.

Getting help from AI (besides being ruled out by the course policies) will actually hurt you, since the point of these questions is for you to gain the practice and experience of working through the problems.

You will need that general skill (of absorbing something by practicing it) in life, and in this semester you will need the specific problem-solving skills that are emphasized in these homeworks.

Processes and threads

In this question, assume a standard system with isolation and memory protection. Further assume that the thread abstraction is implemented by the operating system. That is, thread_create() is a system call.

  1. What do you think are the differences between the implementation of thread_create(func) and the implementation of fork()? (here, func is the address of the function that the thread should begin at).
  2. What do you think are the key differences between the OS’s “process” data structure and whatever data structure it uses to implement a thread?

The uses of threading

Define time-to-completion as the time between when a process begins handling a workload and finishes handling that workload. Is the following statement true always, sometimes, or never? "For a given workload, a multi-threaded process has lower time-to-completion than the equivalent single-threaded process." Explain your answer in 2-3 sentences.

Threads vs. processes

A thread within a process has its own: (Choose all that apply)

A. stack

B. main() function

C. registers

D. global variables

E. program code

F. heap

Race conditions

Identify the potential concurrency issues with the function add below by giving an example. (Hint: what happens when one thread runs add(a,b) while another runs add(b,a)?)

  struct Point {
    int x;
    int y;
  };

  void add(struct Point *a, const struct Point *b) {
    a->x += b->x;
    a->y += b->y;
  }

Concurrency

Based on the following code:

    int i = 0; 

    void
    foo(void *)
    {
        int n = i;
        i = i + 1;
        printf("foo: %d\n", n);
    }

    void
    boo(void *)
    {
        int n = i;
        i = i + 1;
        printf("boo: %d\n", n);
    }

    int
    main(void)
    {
        tid_foo = create_thread(foo); 
        tid_boo = create_thread(boo);

        // wait for threads to finish
        join_thread(tid_foo);
        join_thread(tid_boo);

        printf("main: %d\n", i);
        return 0;
    }
  1. What are the possible outputs of this program?
  2. How could you avoid the race conditions?

Handing in the homework

Use Gradescope; you can enroll in our course with entry code J44YWJ.