
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. pthread_exit is used to explicitly exit a thread.The entire process is terminated due to a call to either the exec or exit subroutines.The thread is canceled by another thread via the pthread_cancel routine.The thread makes a call to the pthread_exit subroutine.The thread returns from its starting routine (the main routine for the initial thread).There are several ways in which a Pthread may be terminated:.As the loop iterates, the value of this memory location changes, possibly before the created threads can access it. It passes the address of variable id, which is shared memory space and visible to all threads. If we do (void*) &id, it's a wrong way of passing data to the child thread. Note that, in the code, we pass the parameter (thread id) to the child thread. Int ret = pthread_create(&my _thread, NULL, &worker _thread, (void*) id) Printf("This is worker_thread #%ld\n", (long)arg) The return value from the pthread_create() call will be zero if it's successful, otherwise, it returns an error. The call also passes the address of a my_thread variable for the worker_thread() to store a handle to the thread. The call to create the thread has a NULL value for the attributes, which gives the thread default attributes. In the code, the main thread will create a second thread to execute worker_thread(), which will print out its message while main thread prints another. Printf("Error: pthread_create() failed\n") Ret = pthread_create(&my _thread, NULL, &worker _thread, NULL) Here is a sample of creating a child 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. While using fork() causes execution to continue in the same location with a different return code, using a new thread explicitly provides a pointer to a function where the new thread should start executing.Ī single argument that may be passed to start_routine. So, we can pass any type of single argument and return a pointer to any type.


We should pass the address of a function taking a pointer to void as a parameter and the function will return a pointer to void. The routine that the thread will execute once it is created. We can specify a thread attributes object, or NULL for the default values.

This identifier enables us to refer to the thread.Īn attribute object that may be used to set thread attributes. When a thread is created, an identifier is written to the memory location to which this variable points. This is a pointer to pthread_t structure.
