CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 7 of 7 · 3 min read

Exercises

Easy

Easy 1: Pool or per-request (20 minutes)

For each case pick a pool or a thread per request, and say why: 10 long jobs once a day; 50,000 requests per second of a few microseconds each.

Done when: per request is acceptable for the first, and a pool is needed for the second.

Hint

Weigh the creation cost against the task time.

Easy 2: Size the pool (20 minutes)

Apply the rule for 8 processors with tasks computing for 5 ms and waiting 45 ms.

Done when: 8 × (1 + 9) = 80.

Hint

Wait time divided by compute time is 9.

Easy 3: Spot the bug (20 minutes)

A worker uses if (count == 0) pthread_cond_wait(...). Describe a case where it removes from an empty queue.

Done when: a description with two workers, one task and one signal: both wake and the second finds the queue empty.

Hint

A signal wakes one waiter, but a broadcast or a late arrival can wake two.

Medium

Medium 1: Run and change the pool (30 minutes)

Compile the pool. Change NWORKERS to 1, 2, 8 and NTASKS to 1,000, and check the total each time against the closed form.

Done when: each total equals the sum of n(n+1)/2 for n up to NTASKS.

Hint

The closed form is n(n+1)(n+2)/6 for the sum of triangular numbers.

Medium 2: Show which worker ran which task (30 minutes)

Make each worker record its own number in a per-task array. Print how many tasks each worker handled.

Done when: four counts adding to the number of tasks, with different values on different runs.

Hint

Pass the worker number as the argument to worker.

Medium 3: Measure thread per task against pool (30 minutes)

Run the 20,000-task program three times, then change the tasks to 100,000 multiplications each. Say how the ratio changes.

Done when: two tables of ratios and a sentence saying the ratio falls as tasks get longer.

Hint

Longer tasks dilute the creation cost.

Hard

Hard 1: Pool shutdown (60 minutes)

Add a function pool_shutdown that waits until the queue is empty and all running tasks are done, then stops the workers. Test with tasks that sleep random times.

Done when: no task is lost, the workers all end, and valgrind or a count shows no leak.

Hint

Track the number of running tasks under the same lock.

Hard 2: Poll with a timeout (60 minutes)

Extend the event-loop program to read from three pipes and print tick every 100 ms when nothing arrives, using the poll timeout.

Done when: ticks appear between messages and every message is printed exactly once.

Hint

The last argument of poll is in milliseconds.

Hard 3: A tiny echo server (60 minutes)

Write a TCP echo server with poll that serves up to 10 clients in one thread. Test with nc localhost PORT in three terminals.

Done when: each client gets its own text back, and a client that disconnects does not stop the others.

Hint

Use listen, accept and a pollfd array, and remove a closed descriptor.