Lab 4 walkthrough — Thread creation
Lab 4 walkthrough — Thread creation
Recorded by Dr. Krithika L.B. Slot lab04-walkthrough
Theory link: 2.3 Threads
Lab 4 walkthrough — Thread creation
Recorded by Dr. Krithika L.B. Slot lab04-walkthrough
Aim. To create and join POSIX threads, pass arguments to them, and collect results.
A thread runs a function inside the same process (Session 2.3). With Pthreads:
pthread_create(&tid, NULL, func, arg) starts func(arg) in a new thread.pthread_join(tid, &ret) waits for it to finish and optionally receives the value it returned.-pthread.Each thread gets its own argument (here, a separate array element — never pass the address of a loop variable that keeps changing).
These programs use POSIX system calls (fork, pthread, shm, semaphore) and must be compiled and run on Linux or WSL — not with Windows MinGW/Turbo C.
#include <stdio.h>
#include <pthread.h>
void *work(void *arg)
{
int n = *(int *)arg;
printf("Thread %d: square of %d is %d\n", n, n, n * n);
return NULL;
}
int main(void)
{
pthread_t tid[3];
int num[3] = {1, 2, 3};
for (int i = 0; i < 3; i++)
pthread_create(&tid[i], NULL, work, &num[i]);
for (int i = 0; i < 3; i++)
pthread_join(tid[i], NULL);
printf("All threads finished\n");
return 0;
}#include <stdio.h>
#include <pthread.h>
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int part[2]; /* result of each thread */
void *sum_half(void *arg)
{
int id = *(int *)arg; /* 0 = first half, 1 = second half */
part[id] = 0;
for (int i = id * 5; i < id * 5 + 5; i++)
part[id] += a[i];
printf("Thread %d sum = %d\n", id, part[id]);
return NULL;
}
int main(void)
{
pthread_t t[2];
int id[2] = {0, 1};
pthread_create(&t[0], NULL, sum_half, &id[0]);
pthread_create(&t[1], NULL, sum_half, &id[1]);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
printf("Total = %d\n", part[0] + part[1]);
return 0;
}gcc threads.c -o threads -pthread./threadsgcc thread_sum.c -o thread_sum -pthread then ./thread_sum$ ./threads
Thread 1: square of 1 is 1
Thread 2: square of 2 is 4
Thread 3: square of 3 is 9
All threads finished$ ./thread_sum
Thread 0 sum = 15
Thread 1 sum = 40
Total = 55pthread_self().pthread_exit() / pthread_join() instead of a global array.Prepare these for the lab evaluation.
Revealed 0A thread shares the address space and resources of its process; a process has its own. Threads are cheaper to create and switch.
It links the POSIX thread library and sets the right compiler flags for thread-safe code.
The whole process exits and all its threads are killed.
All threads would share one variable that keeps changing, so they may read the wrong value (a race).
One-to-one.