Home > Articles

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

4.3 Thread Scheduling

When a process is scheduled to be executed, it is the thread that utilizes the processor. If the process has only one thread, it is the primary thread assigned to a processor. If a process has multiple threads and there are multiple processors, all of the threads are assigned to a processor. Threads compete for processor usage either with all the threads from active processes in the system or just the threads from a single process. The threads are placed in the ready queues sorted by their priority value. The threads in the queue with the same priority are scheduled to processors according to a scheduling policy. When there are not enough processors to go around, then a thread with a higher priority can preempt an executing thread. If the newly active thread is of the same process as the preempted thread, then the context switch is between threads. If the newly active thread is of another process, a process context switch occurs and then the thread context switch is performed.

Table 4-3. Settable Properties for the Thread Attribute Object

Settable Thread Attributes

Functions

Description

detachstate

int pthread_attr_setdetachstate (pthread_attr_t *attr,int detachstate);

The detachstate attribute controls whether the newly created thread is detachable. If detached, the thread's flow of control cannot be joined to any thread.

guardsize

int pthread_attr_setguardsize(pthread_attr_t *attr,size_t guardsize);

The guardsize attribute controls the size of the guard area for the newly created thread's stack. It creates a buffer zone the size of guardsize at the overflow end of the stack.

inheritsched

int pthread_attr_setinheritsched(pthread_attr_t *attr,int inheritsched);

The inheritsched attribute determines how the scheduling attributes of the newly created thread will be set. It determines whether the new thread's scheduling attributes are inherited from the creating thread or set by an attribute object.

param

int pthread_attr_setschedparam(pthread_attr_t *restrict attr,const struct sched_param *restrict param);

The param attribute is a structure that can be used to set the priority of the newly created thread.

schedpolicy

int pthread_attr_setschedpolicy(pthread_attr_t *attr,int policy);

The schedpolicy determines the scheduling policy of the newly created thread.

contentionscope

int pthread_attr_setscope(pthread_attr_t *attr,int contentionscope);

The contentionscope attribute determines which set of threads the newly created thread will compete with for processor usage. A process scope means the thread will compete with the set of threads of the same process; system scope means the thread will compete with system-wide threads (this includes threads from other processes).

stackaddr stacksize

int pthread_attr_setstack(pthread_attr_t *attr,void *stackaddr,size_t stacksize);

The stackaddr and stacksize attributes determine the base address and minimum size in bytes of the stack for the newly created thread.

stackaddr

int pthread_attr_setstackaddr(pthread_attr_t *attr,void *stackaddr);

The stackaddr attribute determines the base address of the stack for the newly created thread.

stacksize

int pthread_attr_setstacksize(pthread_attr_t *attr,size_t stacksize);

The stacksize attribute determines the minimum size in bytes of the stack for the newly created thread.

4.3.1 Thread States

Threads have the same states and transitions mentioned in Chapter 3 that processes have. Figure 4-4 is a duplication of the state diagram 3.4 from Chapter 3. To review, there are four commonly implemented states: runnable, running (active), stopped, and sleeping (blocked). A thread state is the mode or condition a thread is in at any given time. A thread is in a runnable state when it is ready for execution. All runnable threads are placed in a ready queue with other threads with the same priority that are ready to be executed. When a thread is selected and assigned to a processor, the thread is in the running state. A thread is preempted once it has executed for its time slice or when a thread of higher priority becomes runnable. The thread is then placed back into the ready queue. A thread is in the sleeping state if it is waiting for an event to occur or I/O request to complete. A thread is stopped when it receives a signal to stop executing. It remains in that state until it receives a signal to continue. Once the signal is received, the thread moves from the stopped to a runnable state. As the thread moves from one state to another, it undergoes a state transition that signals some event has occurred. When a thread changes from the runnable to the running state it is because the system has selected that thread to run—the thread has been dispatched. A thread is preempted if its makes an I/O request or some other request of the kernel or for some external reason.

04fig04.gifFigure 4-4. Thread states and transitions.

One thread can determine the state of an entire process. The state of a process with one thread is synonymous with the state of its primary thread. If the primary thread is sleeping, the process is sleeping. If the primary thread is running, the process is running. For a process that has multiple threads, all threads of the process would have to be in a sleeping or stopped state in order to consider the whole process sleeping or stopped. On the other hand, if one thread is active (runnable or running) then the process is considered active.

4.3.2 Scheduling and Thread Contention Scope

The contention scope of the thread determines which set of threads a thread will compete with for processor usage. If a thread has process scope, it will only compete with the threads of the same process for processor usage. If the thread has system scope, it will compete with its peers and with threads of other processes for processor usage. For example, in Figure 4-5, there are two processes in a multiprocessor environment of three processors. Process A has four threads and Process B has three threads. Process A has three threads that have process scope and one thread with system scope. Process B has two threads with process scope and one thread with system scope. Process A's threads with process scope competes for processor A and Process B's threads with process scope compete for processor C. Process A and B's threads with system scope compete for processor B.

04fig05.gifFigure 4-5. Scheduling with process and system scope threads in a multiprocessor environment.

Threads should have system scope when modeling true real-time behavior in your application.

4.3.3 Scheduling Policy and Priority

The scheduling policy and priority of the process belong to the primary thread. Each thread can have its own scheduling policy and priority separate from the primary thread. Threads have an integer priority value that has a maximum and minimum value. A priority scheme is used to determine which thread is assigned the processor. Each thread has a priority and the thread with the highest priority is executed before the threads of lower priority. When threads are prioritized, tasks that require immediate execution or response from the system are allotted the processor time it requires. In a preemptive operating system, executing threads are preempted if a thread of higher priority and the same contention scope is available. For example, in Figure 4-5, threads with process scope compete for the processor with threads of the same process that also have process scope. Process A has two threads with priority 3 in which one is assigned the processor. Once the thread with priority 2 becomes runnable, the active thread is preempted and the processor is given to the thread with higher priority. Yet, in Process B, it has two process scope threads that have priority 1, a higher priority than 2. One thread is assigned the processor. Although the other thread with priority 1 is runnable, it does not preempt Process A's thread with priority 2. The thread with system scope and a lower priority is not preempted by any of the threads of Process A or B. They only compete for processor usage with other threads that have system scope.

As discussed in Chapter 3, the ready queues are organized as a sorted list in which each element is a priority level. Each priority level in the list is a queue of threads with the same priority level. All threads of the same priority level are assigned to the processor using a scheduling policy: FIFO, round-robin, or other. With the FIFO (First-In, First-Out) scheduling policy, when the time slice expires the thread is placed at the head of the queue of its priority level. Therefore, the thread will run until it completes execution, it sleeps, or it receives a signal to stop. When a sleeping thread is awakened, it is placed at the end of the queue of its priority level. Round-robin scheduling is similar to FIFO scheduling except the thread is placed at the end of the queue when the time slice expires and the processor is given to the next thread in the queue.

The round-robin scheduling policy considers all threads to be of equal priority and each thread is given the processor for only a time slice. Task executions are interweaved. For example, a program that searches files for specified keywords is divided into two threads. One thread, thread 1, searches for all files with a specified file extension and places the path of the file into a container. Another thread, thread 2, extracts the name of the files from the container, searches each file for the specified keywords, then writes the name of the files that contains all the keywords to a file. If the threads used a round-robin scheduling policy with a single processor, thread 1 would use its time slice to find files and insert the paths into the container. Thread 2 would use its time slice to extract file names and then perform the keyword search. In a perfect world, this interweaves the execution of threads 1 and 2. But thread 2 may execute first when there are no files in the container or thread 1 may only get as far as finding a file, the time slice expiring before it had a chance to insert the file name into the container. This situation requires synchronization, which will be discussed briefly later in this chapter and in Chapter 5. The FIFO scheduling policy allows each thread to run until execution is complete. Using the same example, thread 1 would have time to locate all the files and insert the paths into the container. Thread 2 would then extract the filenames and perform its keyword search on each file. In a perfect world, this would be the end of the program. But thread 2 may be assigned to a processor before thread 1 and there would be no files in the container to search. Thread 1 would then execute, locate, and insert file names into the container but no keyword search would be performed. The program would fail. With FIFO scheduling, there is no interweaving of the execution of these tasks. A thread assigned to a processor dominates the processor until it completes execution. This scheduling policy can be used for applications where a set of threads need to complete as soon as possible. The "other" scheduling policy can be user-defined customization of a scheduling policy. For example, the FIFO scheduling policy can be customized to allow random unblocking of threads.

4.3.3.1 Changing Thread Priority

The priorities of threads should be changed in order to speed up the execution of threads on which other threads depend. They should not be changed in order for a specific thread to get more processor time. This will affect the overall performance of the system. High-priority class threads receive more processor time than threads of a lower class because they are executed more frequently. Threads of higher priority will dominate the processor, preventing other threads of lower priority valuable processor time. This is called starvation. Systems that use dynamic priority mechanisms respond to this situation by assigning priorities that last for short periods of time. The system adjusts the priority of threads in order for threads of lower priority execution time. This will improve the overall performance of the system.

The temptation to ensure that a process or specific thread runs to completion is to give it the highest priority but this will affect the overall performance of the system. Such threads may preempt communications over networks, causing the loss of data. Threads that control the user interface may be drastically affected, causing the keyboard, mouse, and screen response to be sluggish. Some systems prevent user processes and threads from having a higher priority than system processes. Otherwise, system processes or threads would be prevented from responding to critical system changes. Generally speaking, most user processes and threads fall in the category of normal or regular priority.

  • + 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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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