Thread Creation and Synchronization

 

Creation and Synchronization of Threads using pthread_create() and pthread_join()


1. Aim

To study and implement multithreading using POSIX threads and understand thread creation and synchronization using pthread_create() and pthread_join().


2. Objectives

  • To create multiple threads in a process

  • To pass arguments to threads

  • To synchronize threads using pthread_join()

  • To observe concurrent execution of threads


3. Theory

Thread

A thread is the smallest unit of execution within a process.
All threads of a process:

  • Share the same address space

  • Share code and global data

  • Execute independently


pthread_create()

pthread_create() is used to create a new thread.

When called:

  • A new thread is created

  • It starts executing a specified function

  • Both threads run concurrently


pthread_join()

pthread_join() is used for thread synchronization.

  • The calling thread waits

  • Execution resumes only after the specified thread finishes

This prevents premature termination of the main thread.


4. Problem Description

Create two threads:

  • Thread 1 adds two numbers

  • Thread 2 adds another two numbers
    The main thread waits for both threads and prints the largest sum.


5. Algorithm

Main Thread

  1. Declare thread variables

  2. Initialize input values

  3. Create two threads using pthread_create()

  4. Wait for both threads using pthread_join()

  5. Compare results and display the largest sum


Thread Function

  1. Receive input data

  2. Add two numbers

  3. Store result

  4. Exit thread


6. Program (C Implementation)

#include <stdio.h> #include <pthread.h> /* Structure to pass data to thread */ typedef struct { int a; int b; int sum; } data_t; /* Thread function */ void *add(void *arg) { data_t *d = (data_t *)arg; d->sum = d->a + d->b; return NULL; } int main() { pthread_t t1, t2; data_t d1 = {10, 20, 0}; data_t d2 = {15, 25, 0}; pthread_create(&t1, NULL, add, &d1); pthread_create(&t2, NULL, add, &d2); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("Sum calculated by Thread 1 = %d\n", d1.sum); printf("Sum calculated by Thread 2 = %d\n", d2.sum); if (d1.sum > d2.sum) printf("Largest Sum = %d (Thread 1)\n", d1.sum); else printf("Largest Sum = %d (Thread 2)\n", d2.sum); return 0; }

7. Explanation of Important Functions

pthread_create()

pthread_create(&t1, NULL, add, &d1);
  • Creates a new thread

  • Executes the function add()

  • Passes input data using structure


pthread_join()

pthread_join(t1, NULL);
  • Makes the main thread wait

  • Ensures the thread finishes before proceeding


8. Compilation and Execution

gcc thread_example.c -lpthread ./a.out

9. Sample Output

Sum calculated by Thread 1 = 30 Sum calculated by Thread 2 = 40 Largest Sum = 40 (Thread 2)

10. Observations

  • Threads execute concurrently

  • Each thread performs independent computation

  • Main thread waits for completion

  • No race condition occurs


11. Result

The program successfully demonstrated thread creation and thread synchronization using pthread_create() and pthread_join().


Important Functions to Learn

1️⃣ pthread_create()

What does it do?

👉 pthread_create() is used to create a new thread in a process.

When it is called:

  • A new thread is created

  • The new thread starts executing a specified function

  • The parent (main) thread continues execution in parallel


Syntax

pthread_create(thread_id, attributes, function, argument);

Simple Meaning of Each Parameter

ParameterMeaning
thread_id            Stores the ID of the newly created thread
attributes            Thread properties (NULL = default)
function            Function executed by the new thread
argument            Data passed to the function

Simple Example

pthread_create(&t1, NULL, add, &data);

What happens here?

  • A new thread is created

  • The function add() starts executing in that thread

  • &data is passed to the function


Analogy

Think of pthread_create() as:

“Start a new worker to do this job.”


2️⃣ pthread_join()

What does it do?

👉 pthread_join() makes the calling thread wait until another thread finishes execution.


Syntax

pthread_join(thread_id, return_value);

Simple Meaning of Each Parameter

ParameterMeaning
thread_id                        Thread to wait for
return_value                        Value returned by the thread (usually NULL)

Simple Example

pthread_join(t1, NULL);

What happens here?

  • The main thread waits

  • It resumes only after t1 finishes


Analogy

Think of pthread_join() as:

“Wait until this worker finishes before continuing.”


3️⃣ Why are both needed together?

Without pthread_join():

  • Main thread may finish early

  • Program may exit before child threads complete

With pthread_join():

  • Main thread waits

  • Ensures correct and complete execution

Comments

Popular posts from this blog

Operating Systems OS Lab PCCSL407 Semester 4 KTU BTech CS 2024 Scheme - Dr Binu V P

Exploring the /proc file system

ps command