Join and Detach
After launching a thread, your process can join with the thread. To do that, call the join()member function:
std::thread thr(spellcheck);
thr.join();
Alternatively, if you don't want to join with the thread, you can destroy the thread by calling detach():
std::thread thr(spellcheck);
thr.detach();
Each thread is assigned a unique id that you can use for comparing, sorting, and storing threads in an associative container. To obtain the id of an existing thread, call get_id():
thread::id sp_id;
sp_id=thr.get_id();
Data Protection
A mutex provides exclusive ownership for a thread. The <mutex>header defines two categories of mutexes: timed and non-timed mutexes. Each of these categories has a recursive and a non-recursive version:
- std::mutex
- std::recursive_mutex
- std::timed_mutex
- std::recursive_timed_mutex
All mutexes provide member functions for locking and unlocking a mutex. However, the more common approach is to use the std::unique_lock and std::lock_guard class templates. These templates implement the RAII idiom, locking the resource upon initialization and releasing it when they are destroyed. In the following example, lock_guard is used to gain exclusive access to s:
std::mutex mtx;
std::string s;
void f()
{
std::lock_guard<std::mutex> lck(mtx);
all_caps(s);
} // the mutex is released here
If you're looking for a more sophisticated locking mechanism that supports deferred locking and timeouts, use unique_lock instead. The following code attempts to lock a resource with a timeout. The locking operation must happen in 10 milliseconds. Otherwise, the function f()will give up and exit:
#include <date_time> //a new C++0x library
#include <mutex>
std::timed_mutex mtx;
std::string s;
void f()
{
std::unique_lock <std::timed_mutex>
lck(mtx,std::chrono::milliseconds(10));//wait up to 10ms
if(lck) // did the lock succeed?
all_caps(s);
} // the mutex is released here
Pick Up the Threads
The examples shown here are only an appetizer. The new threading library offers much more than that. For instance, std::condition_variable lets a thread sleep until it has been notified by another thread. Additional facilities for ensuring the proper initialization of objects with static storage duration are also provided, as are deferred locks, and thread-localobjects.