Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.
Thread is short for "thread of execution". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread.
In C++0x threads are started using the std::thread
class:
void my_function()
{
// do stuff
}
std::thread my_thread(my_function); // run my_function in its own thread
The new C++0x standard also supports:
- atomic values and operations with the
std::atomic<>
class template,
- mutexes for data protection (
std::mutex
, std::recursive_mutex
, etc.)
- lock classes for ease of managing lock lifetime (
std::lock_guard<>
, std::unique_lock<>
)
std::lock
and std::try_lock
functions to manage acquiring multiple locks at the same time without risking deadlock
- condition variables to ease waiting for an event (
std::condition_variable
, std::condition_variable_any
)
- futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic "how do I return a value from a thread" question.
- thread-safe initialization of local static objects
- the
thread_local
keyword to declare thread-local data
I gave a more detailed overview of the new C++0x thread library in my article on devx.com: Simpler Multithreading in C++0x
I write about multithreading and concurrency in C++ on my blog. I'm also writing a book on the topic: C++ Concurrency in Action.