These problems should be done on your own. We're not going to be grading them strictly (we'll mainly look at whether you attempted them). But they will be reinforcing knowledge and skills, so you should totally work through them carefully.
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.
- What do you think are the differences between the implementation of
thread_create(func)
and the implementation offork()
? (here,func
is the address of the function that the thread should begin at). - 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;
}
- What are the possible outputs of this program?
- How could you avoid the race conditions?
- What are the possible outputs, after you apply your solution to the prior question?
Handing in the homework
Use Gradescope; you can enroll in our course with entry code JBGJKG. (And please feel free to send us feedback about Gradescope.)