4.8 Creating Threads
The Pthreads library can be used to create, maintain, and manage the threads of multithreaded programs and applications. When creating a multithreaded program, threads can be created any time during the execution of a process because they are dynamic. The pthread_create() function creates a new thread in the address space of a process. The thread parameter points to a thread handle or thread id of the thread that will be created. The new thread will have the attributes specified by the attribute object attr. The thread parameter will immediately execute the instructions in start_routine with the arguments specified by arg. If the function successfully creates the thread, it will return the thread id and store the value in the thread parameter.
If attr is NULL, the default thread attributes will be used by the new thread. The new thread takes on the attributes of attr when it is created. If attr is changed after the thread has been created, it will not affect any of the thread's attributes. If start_routine returns, the thread returns as if pthread_exit() had been called using the return value of start_routine as its exit status.
Synopsis
#include <pthread.h> int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg);
If successful, the function will return 0. If the function is not successful, no new thread is created and the function will return an error number. If the system does not have the resources to create the thread or the thread limit for the process has been reached, the function will fail. The function will also fail if the thread attribute is invalid or the caller thread does not have permission to set the necessary thread attributes.
These are examples of creating two threads with default attributes:
pthread_create(&threadA,NULL,task1,NULL); pthread_create(&threadB,NULL,task2,NULL);
These are the two pthread_create() function calls from Example 4.1. Both threads are created with default attributes.
Program 4.1 shows a primary thread passing an argument from the command line to the functions executed by the threads.
Program 4.1
#include <iostream> #include <pthread.h> #include <stdlib.h> int main(int argc, char *argv[]) { pthread_t ThreadA,ThreadB; int N; if(argc != 2){ cout << "error" << endl; exit (1); } N = atoi(argv[1]); pthread_create(&ThreadA,NULL,task1,&N); pthread_create(&ThreadB,NULL,task2,&N); cout << "waiting for threads to join" << endl; pthread_join(ThreadA,NULL); pthread_join(ThreadB,NULL); return(0); }
Program 4.1 shows how the primary thread can pass arguments from the command line to each of the thread functions. A number is typed in at the command line. The primary thread converts the argument to an integer and passes it to each function as a pointer to an integer as the last argument to the pthread_create() functions. Program 4.2 shows each of the thread functions.
Program 4.2
void *task1(void *X) { int *Temp; Temp = static_cast<int *>(X); for(int Count = 1;Count < *Temp;Count++){ cout << "work from thread A: " << Count << " * 2 = " << Count * 2 << endl; } cout << "Thread A complete" << endl; } void *task2(void *X) { int *Temp; Temp = static_cast<int *>(X); for(int Count = 1;Count < *Temp;Count++){ cout << "work from thread B: " << Count << " + 2 = " << Count + 2 << endl; } cout << "Thread B complete" << endl; }
In Program 4.2, task1 and task2 executes a loop that is iterated the number of times as the value passed to the function. The function either adds or multiplies the loop invariant by 2 and sends the results to standard out. Once complete, each function outputs a message that the thread is complete. The instructions for compiling and executing Programs 4.1 and 4.2 are contained in Program Profile 4.1.
Program Profile 4.1
Program Name
program4-12.cc
Description
Accepts an integer from the command line and passes the value to the thread functions. Each function executes a loop that either adds or multiples the loop invariant by 2 and sends the result to standard out. The main line or primary thread is listed in Program 4.1 and the functions are listed in Program 4.2.
Libraries Required
libpthread
Headers Required
<pthread.h> <iostream> <stdlib.h>
Compile and Link Instructions
c++ -o program4-12 program4-12.cc -lpthread
Test Environment
SuSE Linux 7.1, gcc 2.95.2,
Execution Instructions
./program4-12 34
Notes
This program requires a command-line argument.
This is an example of passing a single argument to the thread function. If it is necessary to pass multiple arguments to the thread function, create a struct or container containing all the required arguments and pass a pointer to that structure to the thread function.
4.8.1 Getting the Thread Id
As mentioned earlier, the process shares all its resources with the threads in its address space. Threads have very few resources of their own. The thread id is one of the resources unique to each thread. The pthread_self() function returns the thread id of the calling thread.
Synopsis
#include <pthread.h> pthread_t pthread_self(void);
This function is similar to getpid() for processes. When a thread is created, the thread id is returned to the creator or calling thread. The thread id will not know the created thread. Once the thread has its own id, it can be passed to other threads in the process. This function returns the thread id with no errors defined.
Here is an example of calling this function:
//... pthread_t ThreadId; ThreadId = pthread_self();
A thread calls this function and the function returns the thread id stored in the variable ThreadId of type pthread_t.
4.8.2 Joining Threads
The pthread_join() function is used to join or rejoin flows of control in a process. The pthread_join() causes the calling thread to suspend its execution until the target thread has terminated. It is similar to the wait() function used by processes. This function can be called by the creator of a thread. The creator thread waits for the new thread to terminate and return, thus rejoining flows of control. The pthread_join() can also be called by peer threads if the thread handle is global. This will allow any thread to join flows of control with any other thread in the process. If the calling thread is canceled before the target thread returns, the target thread will not become a detached thread (discussed in the next section). If different peer threads simultaneously call the pthread_join() function on the same thread, this behavior is undefined.
Synopsis
#include <pthread.h> int pthread_join(pthread_t thread, void **value_ptr);
The thread parameter is the thread (target thread) the calling thread is waiting on. If the function returns successfully, the exit status is stored in value_ptr. The exit status is the argument passed to the pthread_exit() function called by the terminated thread. The function will return an error number if it fails. The function will fail if the target thread is not a joinable thread or, in other words, created as a detached thread. The function will also fail if the specified thread thread does not exist.
There should be a pthread_join() function called for all joinable threads. Once the thread is joined, this will allow the operating system to reclaim storage used by the thread. If a joinable thread is not joined to any thread or the thread that calls the join function is canceled, then the target thread will continue to utilize storage. This is a state similar to a zombied process when the parent process has not accepted the exit status of a child process, the child process continues to occupy an entry in the process table.
4.8.3 Creating Detached Threads
A detached thread is a terminated thread that is not joined or waited upon by any other threads. When the thread terminates, the limited resources used by the thread, including the thread id, are reclaimed and returned to the system pool. There is no exit status for any thread to obtain. Any thread that attempts to call pthread_join() for a detached thread will fail. The pthread_detach() function detaches the thread specified by thread. By default, all threads are created as joinable unless otherwise specified by the thread attribute object. This function detaches already existing joinable threads. If the thread has not terminated, a call to this function does not cause it to terminate.
Synopsis
#include <pthread.h> int pthread_detach(pthread_t thread thread);
If successful, the function will return 0. If not successful, it will return an error number. The pthread_detach() function will fail if thread is already detached or the thread specified by thread could not be found.
This is an example of detaching an already existing joinable thread:
//... pthread_create(&threadA,NULL,task1,NULL); pthread_detach(threadA); //...
This causes threadA to be a detached thread. To create a detached thread, as opposed to dynamically detaching a thread, requires setting the detachstate of a thread attribute object and using that attribute object when the thread is created.
4.8.4 Using the Pthread Attribute Object
The thread attribute object encapsulates the attributes of a thread or group of threads. It is used to set the attributes of threads during their creation. The thread attribute object is of type pthread_attr_t. This structure can be used to set these thread attributes:
-
size of the thread's stack
-
location of the thread's stack
-
scheduling inheritance, policy, and parameters
-
whether the thread is detached or joinable
-
the scope of the thread
The pthread_attr_t has several methods that can be invoked to set and retrieve each of these attributes. Table 4-3 lists the methods used to set the attributes of the attribute object.
The pthread_attr_init() and pthread_attr_destroy() functions are used to initialize and destroy a thread attribute object.
Synopsis
#include <pthread.h> int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t *attr);
The pthread_attr_init() function initializes a thread attribute object with the default values for all the attributes. The attr parameter is a pointer to a pthread_attr_t object. Once attr has been initialized, its attribute values can be changed by using the pthread_attr_set functions listed in Table 4-3. Once the attributes have been appropriately modified, attr can be used as a parameter in any call to the pthread_create() function. If successful, the function will return 0. If not successful, the function will return an error number. The pthread_attr_init() function will fail if there is not enough memory to create the object.
The pthread_attr_destroy() function can be used to destroy a pthread_attr_t object specified by attr. A call to this function deletes any hidden storage associated with the thread attribute object. If successful, the function will return 0. If not successful, the function will return an error number.
4.8.4.1 Creating Detached Threads Using the Pthread Attribute Object
Once the thread object has been initialized, its attributes can be modified. The pthread_attr_setdetachstate() function can be used to set the detachstate attribute of the attribute object. The detachstate parameter describes the thread as detached or joinable.
Synopsis
#include <pthread.h> int pthread_attr_setdetachstate(pthread_attr_t *attr, int *detachstate); int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);
The detachstate can have one of these values:
PTHREAD_CREATE_DETACHED PTHREAD_CREATE_JOINABLE
The PTHREAD_CREATE_DETACHED value will cause all the threads that use this attribute object to be detached. The PTHREAD_CREATE_JOINABLE value will cause all the threads that use this attribute object to be joinable. This is the default value of detachstate. If successful, the function will return 0. If not successful, the function will return an error number. The pthread_attr_setdetachstate() function will fail if the value of detachstate is not valid.
The pthread_attr_getdetachstate() function will return the detachstate of the attribute object. If successful, the function will return the value of detachstate to the detachstate parameter and 0 as the return value. If not successful, the function will return an error number. In Example 4.2, the threads created in Program 4.1 are detached. This example uses an attribute object when creating one of the threads.
Example 4.2 Using an attribute object to create a detached thread.
//... int main(int argc, char *argv[]) { pthread_t ThreadA,ThreadB; pthread_attr_t DetachedAttr; int N; if(argc != 2){ cout << "error" << endl; exit (1); } N = atoi(argv[1]); pthread_attr_init(&DetachedAttr); pthread_attr_setdetachstate(&DetachedAttr,PTHREAD_CREATE_DETACHED); pthread_create(&ThreadA,NULL,task1,&N); pthread_create(&ThreadB,&DetachedAttr,task2,&N); cout << "waiting for thread A to join" << endl; pthread_join(ThreadA,NULL); return(0); }
Example 4.2 declares an attribute object DetachedAttr. The pthread_attr_init() function is used to allocate the attribute object. Once initialized, the pthread_attr_detachstate() function is used to change the detachstate from joinable to detached using the PTHREAD_CREATE_DETACHED value. When creating ThreadB, the Detached-Attr is the second argument in the call to the pthread_create() function. The pthread_join() call is removed for ThreadB because detached threads cannot be joined.