Posts

Showing posts with the label MultiThreading

What happens internally in Linux Kernel when Process and Thread is created.

Image
In our post , we have came to known that Linux implements threads as standard processes. Let's see in this post, how they are implemented internally. In C, we use fork() to create new process and pthread_create to create a new thread. Both internally uses clone system call provided by Linux Kernel. Process Creation example: #include <stdio.h> int main() { fork(); return 0; } To find the system call :strace ./fork clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fec70651a10) = 4269 Thread Creation Example: #include <stdio.h> #include <pthread.h> void *func(void *arg) { return NULL; } int main(int argc, char *argv[]) { pthread_t thread; pthread_create(&thread,NULL, func, NULL); return 0; } To find the system call: strace ./thread clone(child_stack=0x7f74bf7a2fb0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|C...

MultiThreading in C Tutorial - Part 8(Semaphore)

API for semaphores: Header file: #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); It is used to initialized the semaphore,with the initial value of the semaphore set to the value passed in the third argument.. pshared is used to indicate whether you want to share the semaphore between process or threads. if pshared value is zero it is shared between threads else it will be shared between processes. If you are trying to initialize already initialized semaphore,the result is undefined behaviour. int sem_destroy(sem_t *sem); Initialized semaphores that are not currently blocked can be destroyed by using sem_destroy api. int sem_wait(sem_t *sem); It decrements the value pointed by the semaphore.If the value is greater than zero then the function returns immediately,if the value is zero then it is blocked until the value is greater than zero so that it can decrement it. int sem_post(sem_t *sem); sem_post increments(unlocks) the ...

MultiThreading in C Tutorial - Part 7 Mutex

Mutexes are used to provide  exclusive access to a shared resource .Mutex stands for Mutual Exclusion. POSIX API's for Mutex: int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); This function initializes the mutex with the attributes passed in the second argument.If the second argument is NULL then default attributes are applied.Upon successful initialization, the state of the mutex will be initialized and unlocked. int pthread_mutex_destroy(pthread_mutex_t *destroy); It is used to destroy the mutex specified in the argument and its state become uninitialized.Once destroyed you can still use it to reinitialize.Note that if you are trying to destroy the mutex when it is locked it will result in undefined behaviour. If you want a  mutex with default attributes, the macro PTHREAD_MUTEX_INITIALIZER can be used. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; The above statement is similar to calling pthread_mutex_init with second ...

MultiThreading in C Tutorial - Part 6(Attributes)

We know that the second argument we pass to the pthread_create is attributes,when we pass it NULL it will take the default attributes.We will see what are the default state of the attributes. Example code to print the default attributes: #include <stdio.h> #include <pthread.h> #include <stdlib.h> void attr_dump(pthread_t thread_id) { pthread_attr_t attr; void *stkaddr; size_t stksize, guardsize; int thread_state, schedpolicy; /* * pthread_getattr_np : gets the attributes of the thread specified * in the first argument */ pthread_getattr_np(thread_id, &attr); printf("Printing Default Attributes\n"); /* * Read stack size and stack address */ pthread_attr_getstack(&attr, &stkaddr, &stksize); printf("Stack Size:%d bytes\n",stksize); printf("Stack Address:%p\n",stkaddr); /* * Read whether it is detached state or joinable state   */ pthread_attr_getdetachstate(&...

Multithreading in C Tutorial - Part 5 (pthread_yield)

Calling pthread_yield api by any thread will give up the cpu to the other threads.The current thread will be placed in the end of the run queue and another thread will be scheduled by the scheduler Syntax:  int pthread_yield(void); Returns 0 on success and error value on error. Example Code: #include <stdio.h> #include <pthread.h> pthread_t tid[2]; void *thread_fn1(void *arg) { int err = pthread_yield(); perror("pthread_yield"); printf("Thread 1 in execution\n"); pthread_exit(NULL); } void *thread_fn2(void *arg) { printf("Thread 2 in execution\n"); pthread_exit(NULL); } int main() { int ret; ret = pthread_create(&tid[0], NULL, thread_fn1, NULL); if (!ret) printf("Thread[%d] created Successfully\n",1); else printf("Thread[%d] not created\n",1); ret = pthread_create(&tid[1], NULL, thread_fn2, NULL); if (!ret) printf("Thread[%d] created Successfully\n...

MultiThreading in C Tutorial - Part 4(pthread_detach)

At any point of time a thread can be in any one of the following states: joinable, detachable.By default if you are not modifying any attributes and has passed NULL as the second argument while the creation of thread(pthread_create) it will be in joinable state. Resources used by Joinable threads cannot be freed by himself, it has to freed by other threads using pthread_join.Resources used by detached threads cannot be freed by other threads,the resources are automatically freed on termination.So it is better to use pthread_detach if you are not doing any synchronization. Syntax:  int pthread_detach(pthread_t pthread); Example Code: #include <stdio.h> #include <pthread.h> void *threadFn(void *arg) { pthread_detach(pthread_self()); sleep(1); printf("Thread Fn\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t tid; int ret = pthread_create(&tid, NULL, threadFn, NULL); if (ret != 0) { perror("Thread Cr...

MultiThreading in C Tutorial - Part3(pthread_exit and pthread_equal)

pthread_exit: Syntax: void pthread_exit(void *retval); pthread_exit has two different roles.If it is used in the main thread,it makes it to wait until all the user level threads terminates.If it is used in a thread function it will work like a exit call. pthread_equal: Syntax: int pthread_equal(pthread_t t1, pthread_t t2); pthread_equal is used by the applications to compare two thread values.If two threads are equal, it returns a non zero value,otherwise it returns 0 Example Program: #include <stdio.h> #include <pthread.h> pthread_t tid[2]; void *thread_fn(void *arg) { if(pthread_equal(tid[0], pthread_self())) printf("Thread 0 in execution\n"); else printf("Thread 1 in execution\n"); pthread_exit(NULL); } int main() { int i; int ret; for (i = 0;i < 2;i++) { ret = pthread_create(&tid[i], NULL, thread_fn, NULL); if (!ret) printf("Thread[%d] created Successfully\n",i+1); else p...

Multithreading in C Tutorial - Part 2(pthread_self)

Each thread created using pthread_create api is assigned an unique id.After the pthread_create is executed successfully,the parent can get the thread id,but what if we want to know the id of the thread while it is in execution,this can be achieved by calling a function pthread_self() Look at the example code to understand: app.c: #include <stdio.h> #include <pthread.h> void *thread_fn(void *arg) { sleep(1); printf("ID of thread in thread_fn is %u\n",pthread_self()); return NULL; } int main(int argc, char *argv[]) { pthread_t tid; printf("In Main Fn\n"); pthread_create(&tid, NULL, thread_fn, NULL); printf("ID of thread in main:%u\n",tid); pthread_join(tid, NULL); printf("After the thread execution\n"); return 0; } In order to compile this application you have to pass -lpthread as an argument to gcc gcc pthread_self.c -0 pthread_self -lpthread O/P: In Main Fn ID of thread in main:3...

Multithreading in C Tutorial- Part 1

What is a Thread? Thread is a smallest sequence of instructions that can be executed independently by the scheduler.Process is nothing but multiple threads of execution running asynchronously. We will start with creating a thread in C,the API used to create a thread is pthread_create.The arguments to this function are First argument :      pthread_t *thread ,(Thread id) Second Argument: const pthread_attr_t *attr ,(Attributes if any) Third Argument: void *(*start_routine)(void *) ,(the function which should be called) Fourth Argument: void *arg,(Arguments to the function) We will see a simple example code here: #include <stdio.h> #include <pthread.h> void *ThreadFn(void *arg) { sleep(1); printf("In Thread Fn\n"); return NULL; } int main(int argc, char *argv[]) { pthread_t tid; printf("Before Thread\n"); pthread_create(&tid, NULL, ThreadFn, NULL); /*   *pthread_join blocks the calling thread until the * th...