CSSE 132 Mini-reading · Concurrency / pthreads
Socket Concurrency: Getting Started with Threads
Follow two workers, track their inputs, and reason about what can happen first. Allow about 8–10 minutes, plus practice.
Why This Matters
A server that handles one client completely before accepting the next can keep other clients waiting. Threads let one program make progress on several activities. The same tools let separate workers calculate squared values, as you will do in Worksheet 25.
Core Idea: Several Workers, One Process
A process is a running program. A thread is one flow of execution inside it. Your C program begins with a main thread; pthreads lets it start more threads that run functions.
Concurrency means tasks can make progress during overlapping periods. One core can switch between them. Parallelism means tasks actually execute at the same time, for example on different cores. Creating threads makes concurrency possible; it does not guarantee a speedup.
Threads in one process share globals and heap storage. Each has its own stack and execution state. A pointer can still give another thread access to an object on your stack: separate stacks do not make pointed-to data private. Keep that object alive while the worker uses it.
Worked Examples
1. Start two workers and wait for both
This example passes a different integer address to each worker. It includes basic error checks; pthread calls return zero on success and an error number on failure.
| C code | What this does |
|---|---|
| The worker receives one pointer. Cast it to the original pointer type, then dereference to read the integer. Returning NULL finishes this worker; it does not end the other threads. |
| Store the first thread’s ID in t0. The new thread calls worker with &a. Main continues; the worker may start before or after main reaches its next statement. |
| Start a second worker using &b. If creation fails, wait for the first worker before leaving main. |
| Each join waits for that worker to finish. Both have finished before All done! prints. The local inputs remain alive until main returns. |
Compile with gcc -Wall -Wextra -pthread threads.c -o threads, then run ./threads. The two worker lines may appear in either order. Joining t0 first does not make t0 run first: both threads were already started. If a worker has finished, joining it need not wait.
2. Read the four arguments
pthread_create(&t0, NULL, worker, &a);
&t0 is a pthread_t *: an output location for the ID. The first NULL selects default attributes. worker names the function to run; do not call it here as worker(...). The last argument is the input pointer, converted to void *. Passing an address does not copy the pointed-to object.
For several inputs, define a struct, create one instance for each worker, and pass each instance’s address. For example, a task can hold an integer ID and a float weight. Inside the worker, cast arg to a pointer to that struct and read its fields with ->.
3. Divide a calculation without duplicating work
Suppose three workers must examine array indices 0 through 11. Give them starting indices 0, 1, and 2, and advance each by 3:
| Start | Indices examined |
|---|---|
| 0 | 0, 3, 6, 9 |
| 1 | 1, 4, 7, 10 |
| 2 | 2, 5, 8, 11 |
Every index appears once. Each worker needs its own stable start value. Store starts in separate array elements; keep the array allocated until all workers have joined. Create all workers in one loop, then join them in another. Creating and immediately joining each worker would make these tasks run one after another.
4. Connect threads to socket servers
The main thread can keep the listening socket and call accept repeatedly. A worker handles the connected socket returned for one client, then closes that connection when finished. Meanwhile, main can accept the next client. A worker blocked waiting for its client’s bytes need not stop other workers.
Give each worker its own stable storage for its connected descriptor. Passing every worker the address of one reused accept-loop variable is unsafe: main might overwrite it before a worker reads it. Threads share the process’s descriptors, so closing a descriptor in main also affects a worker using it. Decide which thread owns cleanup. This is a design sketch; a full server must also arrange to join workers or otherwise manage their completion.
Common Mistakes
- Passing &i from a changing loop: every worker receives the same address. Use a separate input object per worker.
- Freeing inputs too soon: starting a thread does not mean it has read its input. Join before releasing storage it still needs.
- Assuming join orders earlier actions: join waits for completion; it does not control which worker prints first.
- Updating a shared counter without protection: counter++ reads, adds, and writes. Two workers can read the same old value and overwrite an update. This illustrates a data race; in C, unsynchronized conflicting accesses cause undefined behavior. Neither join nor volatile makes that update safe. The next topic, mutual exclusion, uses a mutex to protect shared updates.
Quick Reference
#include <pthread.h>and compile with-pthread.- Worker signature:
void *worker(void *arg); return NULL when no result is needed. pthread_create(&t, NULL, worker, input_ptr): start a worker and store its ID.pthread_join(t, NULL): wait for that worker; ignore its return pointer.- Separate stable inputs → create workers → join workers → release inputs.
Check Yourself: Practice Exercises
Try these before opening the answers. Assume thread creation and joining succeed.
- Trace ordering. In example 1, list the two possible line orders. Could All done! appear between the worker lines? Explain.
- Explain a call. For
int a = 7;, explain &a, arg, and *ptr in the worker. Why does the first argument use &t0 while join uses t0? - Repair an input bug. A loop starts four workers with
pthread_create(&threads[i], NULL, worker, &i). Explain the problem and describe storage and cleanup that fix it. Extend your design to pass an ID and a weight. - Divide the work. Four workers examine indices 0 through 9. List each worker’s indices using starts 0–3. What is the step size? Why are there no gaps or duplicates?
- Reason about a server. Main accepts client A, starts a worker, then immediately joins it before accepting B. Why can B still wait? Move the join conceptually, and explain why the two workers need separate descriptor storage.
Answers
Show the answers and reasoning
- Worker 1, Worker 2, All done!; or Worker 2, Worker 1, All done! Both successful joins finish before the last print, so it cannot appear between worker lines.
- &a is the integer’s address. arg receives that address as a void pointer; *ptr reads 7 after converting back to int *. Create needs a location to write the ID; join receives the stored ID of the thread to wait for.
- All workers share the changing i object, and the loop can modify it while workers read it. Use four array elements, initialize each, and pass each element’s address. Keep them alive until all joins complete. For multiple inputs, use an array of structs with id and weight fields.
- Start 0: 0, 4, 8; start 1: 1, 5, 9; start 2: 2, 6; start 3: 3, 7. Step by 4. Every index has exactly one remainder when divided by 4, which identifies its worker.
- Main waits for A’s worker before accepting B. Let main accept and start other workers before waiting for their completion. Give each worker a separate task object so accepting B cannot overwrite A’s descriptor input. Keep each object alive until its worker finishes, and let its designated owner close the connection.
Next Step
Use the same reasoning on Worksheet 25: explain create and join, pass each worker its own input, and calculate three squared values. Trace which array element each worker reads before filling in code.