💻

Understanding Multithreading in C Programming

Nov 27, 2024

Lecture on Multithreading in C

Introduction to Threads

  • A thread is a sequence of execution within a process.
  • Threads are known as "lightweight processes."

Differences between Process and Thread

  • Threads are not independent; they share the code section, data section, and OS resources (like files and signals).
  • Each thread has its own program counter (PC), register set, and stack space.

Why Use Multithreading?

  • Improves application performance through parallelism.
  • Example: Multiple tabs in a browser can be different threads.
  • Threads are faster due to:
    • Faster creation
    • Faster context switching
    • Easier termination
    • Faster communication

Multithreading in C

  • C does not support multithreading by language standard like Java.
  • "POSIX Threads (Pthreads)" is a standard for implementing threads in C.
  • Pthread can be implemented using the GCC compiler.

Demonstration of Pthread Functions

  • Example C program illustrating basic pthread usage: #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void* myThreadFun(void* vargp) { sleep(1); printf("Printing GeeksQuiz from Thread \n"); return NULL; } int main() { pthread_t thread_id; printf("Before Thread\n"); pthread_create(&thread_id, NULL, myThreadFun, NULL); pthread_join(thread_id, NULL); printf("After Thread\n"); exit(0); }
  • pthread_create: Creates a new thread.
    • Takes 4 arguments: pointer to thread ID, attributes, function name, and function arguments.
  • pthread_join: Waits for the thread to terminate.

Compiling the Program

  • Use the following command to compile with pthreads: gcc multithread.c -lpthread ./a.out

Multiple Threads with Global and Static Variables

  • Threads share the data segment, including global and static variables.
  • Example program showing multiple threads accessing shared data: #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int g = 0; void* myThreadFun(void* vargp) { int myid = getpid(); static int s = 0; ++s; ++g; printf("Thread ID: %d, Static: %d, Global: %d\n", myid, ++s, ++g); } int main() { int i; pthread_t tid; for (i = 0; i < 3; i++) pthread_create(&tid, NULL, myThreadFun, NULL); pthread_exit(NULL); return 0; }
  • Note: Accessing global variables in threads requires careful handling, ideally using mutexes to avoid conflicts.

References

  • Links provided for more information on POSIX threads and additional reading materials.

Study Tips

  • Understand how threads share resources compared to processes.
  • Practice with example programs to solidify multithreading concepts.
  • Learn to use synchronization primitives like mutexes when working with shared data in threads.