Skip to main content

Multithreading advantages and C program

Short answer

Multithreading improves responsiveness, resource sharing, economy, CPU utilization, scalability, and simplifies program structure. A C program creates POSIX threads with pthread_create to run a print function concurrently and uses pthread_join to wait for completion.

What are the advantages of multithreading program? Write a simple multithreading program in C.

Advantages of multithreading

  • Responsiveness: the program keeps working even if one thread is blocked or slow.
  • Resource sharing: threads share code, data and files of the process, so communication is simple and fast.
  • Economy: thread creation and context switching take less time and memory than for processes.
  • Better CPU utilisation: the CPU is busy with another thread while one waits for I/O.
  • Scalability: threads run in parallel on multi-core processors.
  • Simpler program structure: each activity gets its own thread.

C program using POSIX threads

#include <stdio.h>
#include <pthread.h>

/* function executed by each thread */
void *print_message(void *arg)
{
    char *name = (char *)arg;
    for (int i = 1; i <= 3; i++)
        printf("%s: count %d\n", name, i);
    return NULL;
}

int main(void)
{
    pthread_t t1, t2;                       /* thread identifiers */

    /* create two threads running the same function */
    pthread_create(&t1, NULL, print_message, "Thread-1");
    pthread_create(&t2, NULL, print_message, "Thread-2");

    /* wait for both threads to finish */
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("Main: both threads finished\n");
    return 0;
}

Compile with gcc prog.c -o prog -lpthread. Output (order of the two threads may vary): Thread-1: count 1, 2, 3 and Thread-2: count 1, 2, 3, then "Main: both threads finished". pthread_create starts a thread and pthread_join makes main wait for it.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 6 questions →