*************** What is Thread? *************** Thread is called as a light weight process. When a new thread is created, it starts executing in the same process area. It shares the process memory space. But it executes concurrently with the main thread. i.e., main thread(main function) and child thread executes concurrently. ********************************* Advantage of Thread over Process. ********************************* a)Time required to create thread is lesser than the time required to create process. While creating new process (ex: fork, fork is a system call used in UNIX to create new process ) Operating System has to allocate memory space, dump all the file descriptors, copy data etc., this requires a lot of CPU time. Creation of new thread doesn't require all these things. Hence creation of thread is much much faster than creation of new process. b)Switching between threads is faster than processes. Switching between process requires saving address locations into registers, saving the process state, swap out the inactive process, swap in active process etc., Switching between threads doesn't require all these things as all the threads run in the same process context. c)Communication overhead is lesser in threads than processes. Since threads share the same global memory space they can be communicated easily where as Processes requires IPC(Shared memory, Message Queues, Semaphores etc.,) to communicate. d)Time required to terminate a thread is lesser than time required to terminate process. **************** Creating Threads **************** ============ UNIX(POSIX) ============ Threads can be created in UNIX using POSIX library. POSIX threads are portable across different UNIX flavors. Header files , sample program(mythread.c) /****************************************************/ #include #include #include void *thread_routine(void *arg) { short l_iloop; for(l_iloop=0;l_iloop<5;l_iloop++) { printf("Hello from thread\n"); sleep(1); } return NULL; } int main() { pthread_t l_thID; short l_iloop; if(pthread_create(&l_thID,NULL,thread_routine,NULL)) { printf("Error in creating thread\n"); exit(0); } else { for(l_iloop=0;l_iloop<5;l_iloop++) { printf("Hello from main\n"); sleep(1); } } pthread_join(l_thID,NULL); return 0; } /***************************************************/ Above program creates one thread. Ok, let us compile the above program and execute, later we shall try to understand what all the things happened in this program. To compile the program save the program as mythread.c and type the following. $ gcc mythread.c -o mythread -lpthread libpthread.so is POSIX thread library.It should be linked using -lpthread at the time of compilation. To run the program type $ ./mythread Observe the output generated. Hello from thread Hello from main Hello from main Hello from thread Hello from main Hello from thread Hello from main Hello from thread Hello from main Hello from thread Main function and thread function executed concurrently. Let us try to understand the thread functions pthread_t pthread_create(pthread_t *thid, pthread_attr_t *attr, void *(*fp)(void *), void *arg); int pthread_join(pthread_t thid,void ** ret); ============== pthread_create ============== First argument is address of thread id. Thread id is of type pthread_t. Second argument is address of thread attribute structure. We shall discuss about thread attributes in future. Since we are at basic level we can ignore thread attributes. Pass NULL as the second argument. Third argument is function pointer which takes address of thread routine. Fourth argument is address of argument. Arguments can be passed to a thread. This will be discussed in future. pthread_create returns 0 on success and any other value indicate failure cases. ============ pthread_join ============ First argument is thread id with which it wants to join. We should call pthread_join to make main thread wait for child thread. Otherwise as soon as the main thread is terminated child thread will also be terminated. Second argument is pointer to a pointer. It will be filled with return value returned by the thread. Following example demonstrates the use of pthread_join pthread_join returns 0 on success,any other value indicates failure cases. sample program(mythreadjoin.c) ++++++++++++++ /****************************************************/ #include #include #include void *thread_routine(void *arg) { short l_iloop; for(l_iloop=0;l_iloop<10;l_iloop++) { printf("Hello from thread\n"); sleep(1); } return NULL; } int main() { pthread_t l_thID; short l_iloop; if(pthread_create(&l_thID,NULL,thread_routine,NULL)) { printf("Error in creating thread\n"); exit(0); } sleep(5); return 0; } /***************************************************/ Following output will be generated when the above program is executed. Hello from thread Hello from thread Hello from thread Hello from thread Hello from thread Here child thread executes only for 5 loops(5secs).Main thread was alive only for 5 seconds, hence as long as main thread is alive child thread was executing, once main thread is exited child thread is also killed. To avoid this pthread_join is used. ============ Windows(SDK) ============ In windows threads can be creating using Win32 SDK Header files sample program(mywinthread.c) /****************************************************/ #include #include #include #include #include void thread_routine(void *arg) { short l_iloop; for(l_iloop=0;l_iloop<5;l_iloop++) { printf("Hello from thread\n"); Sleep(1); } return; } int main() { short l_iloop; if(_beginthread( thread_routine, 0, NULL )==-1) { printf("Error in creating thread\n"); exit(0); } else { for(l_iloop=0;l_iloop<5;l_iloop++) { printf("Hello from main\n"); Sleep(1); } } return 0; } /****************************************************/ To compile the program save the program as mywinthread.c and type the following.(Microsoft VC++ should be installed in your machine to compile the above program) c:\>vcvars32 This batch file initializes the VC++ related variables(ex: include files etc.,) c:\> cl /MT -c mywinthread.c This command generated mywinthread.obj file /MT is multithread support option. c:\>LINK /out:mywinthread.exe mywinthread.obj This command generates mywinthread.exe file To run the program c:\>mywinthread Let us try to understand the thread functions in Windows. ============ _beginthread ============ unsigned long _beginthread( void( __cdecl *start_address )( void * ), unsigned stack_size, void *arglist ); First argument is address of thread routine function. Second argument is stack_size, If programmer want to set the stack size, size can be passed, otherwise pass 0. Default memory will be allocated. Third argument is address of the argument passed to thread routine. In windows SDK there is no join mechanism(like pthread_join).Programmer has to take care of main thread. Synchronizing thread execution, setting threads attributes will be discussed in future articles