Home > Articles

  • Print
  • + Share This
This chapter is from the book

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.


#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:


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]);
   cout << "waiting for threads to join" << endl;

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



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


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


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.


#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.


#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.


#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:


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.


#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. 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.


#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:


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]);
   cout << "waiting for thread A to join" << endl;


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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020