Book Image

The C++ Standard Library - Second Edition

By : Rainer Grimm
Book Image

The C++ Standard Library - Second Edition

By: Rainer Grimm

Overview of this book

Standard template library enables programmers to speed up application development using the built-in data structures and algorithms in their codes. The C++ Standard Library is a comprehensive guide to the updated library of classes, algorithms, functions, iterators, and containers and serves as the best reference to the current C++ 17 standard. Starting with the introduction and history of the standard library, this book goes on to demonstrate how quickly you can manipulate various C++ template classes while writing your applications. You'll also learn in detail the four types of STL components. Then you'll discover the best methods to analyze or modify a string. You'll also learn how to make your application communicate with the outside world using input and output streams and how to use the non-owning string objects with regular strings. By the end of this book, you'll be able to take your programming skills to a higher level by leveraging the standard C++ libraries.
Table of Contents (19 chapters)
Free Chapter
1
Reader Testimonials
8
6. Adaptors for Containers
19
Index

Thread Local Data

By using the keyword thread_local, you have thread local data also known as thread local storage. Each thread has its copy of the data. Thread-local data behaves like static variables. They are created at their first usage, and their lifetime is bound to the lifetime of the thread.

Thread local data
// threadLocal.cpp 
...
std::mutex coutMutex;
thread_local std::string s("hello from ");

void addThreadLocal(std::string const& s2){
  s+= s2;
  std::lock_guard<std::mutex> guard(coutMutex);
  std::cout << s << std::endl;
  std::cout << "&s: " << &s << std::endl;
  std::cout << std::endl;
}

std::thread t1(addThreadLocal, "t1");
std::thread t2(addThreadLocal, "t2");
std::thread t3(addThreadLocal, "t3");
std::thread t4(addThreadLocal, "t4");

Each thread has its copy of the thread_local string, therefore, each string s modifies its string independently...