A thread library in C ++ native_handle()
member functions by using platform-specific API allows direct manipulation of the underlying implementation.
In order to run concurrently function requires the use of specific functions, and objects to manage the various threads. C ++ header file
A simple Hello, Concurrent World program:
#include <iostream>
#include <thread> //①
void hello() //②
{
std::cout << "Hello Concurrent World\n";
}
int main()
{
std::thread t(hello); //③
t.join(); //④
}
Which calls the method std::thread
, it is still visible std domain; simultaneously join
function is to ensure that t
thread of execution after the completion of main
the main thread until the end.
Start a thread
Thread starts when the thread object is created, namely construction thread std::thread
will start object. That is to say we need to set a shared variable only mutual control between threads can be achieved.
- Method three constructs:
std::thread my_thread(background_task); // 1
std::thread my_thread((background_task())); // 2
std::thread my_thread{background_task()}; // 3
- After starting the thread, is a clear need to wait for the end of the thread (join style), or let it run autonomously (separate)
t.detach(); //(分离式),new和current线程无关
t.join(); //(加入式),阻塞current线程,执行新线程
- Modify variables between threads is required
std::ref()
to convert the data to reference data:
std::thread t(update_data_for_widget,w,std::ref(data));
Synchronization of data security
std::mutex mt;
void addmethod(int a)
{
mt.lock();
addprocessing(...);
mt.unlock();
}
void deletemethod(int a)
{
mt.lock();
deleteprocessing(...);
mt.unlock();
}
Use unique_lock or lock_guard achieve locked.
std::mutex mt;
void addmethod(int a)
{
std::unique_lock<std::mutex> lock(mt);
addprocessing(...);
}
void deletemethod(int a)
{
std::unique_lock<std::mutex> l(mt);
deleteprocessing(...);
}