Rc = pthread_create(&threads, &attr, wait, (void *)i ) Ĭout << "Error:unable to create thread," << rc << endl Pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) Ĭout << "main() : creating thread, " << i << endl My_data = (struct thread_data *) threadarg Ĭout << "Thread with id : " << tid << ". Each thread prints a "Hello World!" message, and then terminates with a call to pthread_exit().
This simple example code creates 5 threads with the pthread_create() routine. Otherwise, they will be automatically terminated when main() finishes. If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist.
Here pthread_exit is used to explicitly exit a thread. There is following routine which we use to terminate a POSIX thread − There is no implied hierarchy or dependency between threads. Once created, threads are peers, and may create other threads. The maximum number of threads that may be created by a process is implementation dependent. NULL may be used if no argument is to be passed. It must be passed by reference as a pointer cast of type void. The C++ routine that the thread will execute once it is created.Ī single argument that may be passed to start_routine. You can specify a thread attributes object, or NULL for the default values. Here is the description of the parameters − Sr.NoĪn opaque, unique identifier for the new thread returned by the subroutine.Īn opaque attribute object that may be used to set thread attributes. This routine can be called any number of times from anywhere within your code. Here, pthread_create creates a new thread and makes it executable. Pthread_create (thread, attr, start_routine, arg)
The following routine is used to create a POSIX thread −
POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. Instead, it relies entirely upon the operating system to provide this feature. Each part of such a program is called a thread, and each thread defines a separate path of execution.Ĭ++ does not contain any built-in support for multithreaded applications. Thread-based multitasking deals with the concurrent execution of pieces of the same program.Ī multithreaded program contains two or more parts that can run concurrently. Process-based multitasking handles the concurrent execution of programs. In general, there are two types of multitasking: process-based and thread-based. Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently.