Skip to main content

Section 4.2 Thread API

This small section covers book chapter 27, a relatively small chapter that discusses the POSIX threads API for creating and working with threads. Start with the introduction and section 27.1, about creating threads.

Practice 4.2.1.

The following statements describe the arguments to the pthread_create function. Order them according to their order in the function definition.
Read section 27.2, about how to wait for a thread to complete.

Practice 4.2.2.

    True or False: Unlike in the process API where we could wait for any of our process children to finish, in the thread API we have to wait for a specific thread to finish.
  • True.

  • False.

Practice 4.2.3.

The function used to wait for a thread to complete is called:
  • pthread_join
  • pthread_wait
  • join
  • wait
  • finish_already

Practice 4.2.4.

    True or False: The return value of the function used to wait for a thread is exactly the value that the function running in the thread returns.
  • True.

  • Take another look at the second parameter.
  • False.

  • Take another look at the second parameter.

Practice 4.2.5.

    True or False: Some programs like web servers may start threads but never wait for them to finish. For example worker threads that are perpetually given tasks to do from the main thread.
  • True.

  • False.

Read section 27.3 about using locks.

Practice 4.2.6.

    True or False: If a thread reaches a pthread_mutex_lock call and another thread holds the lock at the time, then the call returns 0.
  • True.

  • Read this section again carefully. The call will just block there waiting for the lock to be released.
  • False.

  • Read this section again carefully. The call will just block there waiting for the lock to be released.

Practice 4.2.7.

The usual way to initialize a lock variable is to use:
  • pthread_mutex_init
  • lock_init
  • initialize
  • Not need to initialize.

Practice 4.2.8.

Read section 27.4 about the concept of condition variables. This is a tricky section, read it carefully.

Practice 4.2.9.

Study the code blocks at the bottom of page 7 and the top of page 8. The first block appears to wait forever within the lock block until ready == 0. The second block sets ready = 1 inside a lock block. How will this second block ever get to do its job if the first block is already holding the lock?
  • You are right, it can’t, the book has a mistake!
  • Multiple threads can hold the lock at the same time, not a problem.
  • The Pthread_cond_wait call actually releases the lock when it starts, and reaquires it before it returns.
Read the remaining sections, 27.5 and 27.6. Make sure to also read the ASIDE on the next page.
You have attempted of activities on this page.