Download presentation
Presentation is loading. Please wait.
1
Threads in C Caryl Rahn
2
What is a thread? Also known as lightweight processes
A single sequence stream within a process Threads are not independent of one another like processes A thread shares with other threads: code section Data section OS resources (open files and signals) A thread does have its own: program counter (PC) Register set Stack space
3
Why use Multithreading
Way to improve an application through parallelism For example, a browser has multiple tabs Threads are faster than processes because Thread creation is faster Context switching between threads is much faster Threads can be terminated easily Communication between threads is faster
4
C and Multithreading Multithreading is not supported by the language standard POSIX threads (Pthreads) are implemented in the gcc compiler You must include pthread.h You must link the program with the pthreads library Include the –lpthread option on the compile line
5
Sample pthread_create has 4 arguments
#include <stdio.h> #include <stdlib.h> #include <pthread.h> // A normal C function that is executed as a thread when its name // is specified in pthread_create() void *myThreadFun(void *vargp) { sleep(1); printf("In Thread \n"); return NULL; } int main() pthread_t tid; printf("Before Thread\n"); pthread_create(&tid, NULL, myThreadFun, NULL); pthread_join(tid, NULL); printf("After Thread\n"); exit(0); pthread_create has 4 arguments The first is a pointer to the thread_id set by this function. The third is NULL The third is the name of the function to be executed for the thread to be created. The fourth is used to pass arguments to the thread Variable thread_id is of type pthread_t is an integer used to identify the thread in the system After declaring thread_id pthread_create() function is called to create a thread. pthread_join() is like a wait() for processes. It blocks the calling process until the thread with an identier equal to the first argument terminates
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.