📖
Go C++
  • Introduction
  • Chapter 1: What You Must Know First
    • Virtual Address Space of Process: Memory Partition and Layout
    • Function Call: Stack Frame
    • Program Compiling and Linking
  • Chapter 2: C++ Basics Improvement
    • Default Parameters
    • Inline Function
    • Function Overloading
    • new and delete
    • const and Pointers
    • References in Detail
  • Chapter 3: Object-Oriented Principles
  • Class and Object
  • Constructor and Destructor
  • Shallow Copy and Deep Copy
  • Initializer List
  • Various Member Functions
  • Pointer to Class Members
  • Chapter 4: Template Programming
  • Function Templates
  • Class Templates
  • Memory Allocators
  • Chapter 5: Operator Overloading
    • Operator Overloading
    • Introduction to Iterators
    • Issues of Iterator Invalidation
    • More about new and delete
    • Overloading of new and delete: Object Pool
  • Chapter 6: Inheritance and Polymorphism
    • Look inside Inheritance
    • More about Inheritance
    • Virtual Functions, Static Binding and Dynamic Binding
    • More about Virtual Functions
    • Understanding Polymorphism
    • Abstract Classes
    • Frequently Asked Interview Questions: Polymorphism
  • Chapter 7: Multiple Inheritance
    • Virtual Inheritance and Virtual Base Classes
    • Diamond Problem
    • Four Kinds of Type Conversions
  • Chapter 8: Standard Template Library
    • Sequence Containers
    • Container Adaptors
    • Associative Containers
    • More about Iterators
    • Function Objects
    • Generic Algorithms, Binders and Lambda Expressions
  • Chapter 9: Object Optimization
    • Behind the Object
    • Optimizing Objects in Functions
    • Member Functions with Rvalue References
    • Move Semantics and Perfect Forwarding
  • Chapter 10: Smart Pointers
    • Smart Pointers
    • Smart Pointers without Reference Counting
    • Smart Pointers with Reference Counting
    • Custom Deleters
  • Chapter 11: Function Objects and Binders
    • More about Binders
    • Introduction to std::function
    • Template Specialization and Argument Deduction
    • More about std::function
    • std::bind(): A Simple Thread Pool
    • More about Lambda Expressions
  • Chapter 12: Multithreading
    • Important Features in C++11
    • Multithreaded Programming with std::thread
    • Mutual Exclusion
    • Producer-Consumer Problem
    • Atomic Operations
    • Thread Visibility and volatile
  • Chapter 13: Design Patterns
    • Singleton Pattern
    • Factory Pattern
    • Proxy Pattern
    • Decorator Pattern
    • Adapter Pattern
    • Observer Pattern
Powered by GitBook
On this page

Was this helpful?

  1. Chapter 12: Multithreading

Multithreaded Programming with std::thread

std::thread is a class that encapsulates multithreading APIs of the operating system. Different operating systems has different API functions. For example, createThread() is used to create a thread in Windows, while pthread_create() is used instead in Linux. With std::thread, programmers can write multithreaded programs more easily. To use std::thread, we should include the thread library:

#include <thread>

We can start a thread by creating a thread object with the thread function. In the following example, we create a thread t which executes function threadHander(). The thread starts to execute after it is created.

join() blocks the current thread, and wait for the child thread to terminate. The current thread continues to run only after the child thread has been terminated.

void threadHandler() {
    cout << "Hello World!" << endl;
}
​
int main() {
    thread t(threadHandler);
    t.join();
    cout << "Thread Done!" << endl;
    return 0;
}

The above example has the following output:

Hello World!
Thread Done!

We can also pass arguments into the thread function. In the following example, we have a thread function which sleeps the thread for several seconds. We use this_thread::sleep_for() for sleeping and chrono::seconds() for the number of seconds.

void threadHandler(int sec) {
    this_thread::sleep_for(chrono::seconds(sec));
    cout << "Hello World!" << endl;
}
​
int main() {
    thread t(threadHandler, 2);
    t.join();
    cout << "Thread Done!" << endl;
    return 0;
}

So far we use join() to make the main thread wait for the child thread to terminate. But what if we don't do this? When the main thread finishes its running, it will check if there are child threads which have not finished yet. If so, the process will terminate abnormally.

int main() {
    thread t(threadHandler, 2);
    // t.join();
    cout << "Thread Done!" << endl;
    return 0;   // ERROR
}

If we don't want the main thread to wait for the child thread, we can use detach(). detach() will separate the child thread with the main thread. After the process terminates, all the unfinished threads will be terminated as well.

int main() {
    thread t(threadHandler, 2);
    t.detach();
    cout << "Thread Done!" << endl;
    return 0;
}

In all, join() ensures that the main thread can not terminate before the child thread is terminated, while detach() does not. We should always remember to use either join() or detach() after a thread is created.

PreviousImportant Features in C++11NextMutual Exclusion

Last updated 4 years ago

Was this helpful?