General class member function thread format Std::thread T1 (& Class Name:: Function,& instantiation object, parameter ...) | | Std::thread T1 (std::bind (&& class Name:: Function,& Instantiate object, Parameters ...)
1#include <iostream>2#include <mutex>3#include <thread>4#include <vector>5#include <string>6#include <condition_variable>7#include <future>8 9 TenTemplate<typename t> One classVector_safe A { - Public: -Vector_safe (): Ready (false), Proccess (false){} the Public: - voidPush (t&value) - { -Std::unique_lock<std::mutex>M_guard (mut); + Vec.push_back (value); -ready=true; + M_guard.unlock (); A Condit_va.notify_one (); at } - voidGet_and_pop (t&value) - { -Std::unique_lock<std::mutex>M_guard (mut); -Condit_va.wait (m_guard,[ This](){returnReady;});//wait-------thread completion data; - inValue=Vec.front (); - Vec.pop_back (); toproccess=true; + M_guard.unlock (); - the } * Private: $Std::vector<t>Vec;Panax Notoginseng Std::mutex Mut; - std::condition_variable Condit_va; the BOOLReady ; + BOOLproccess; A the }; +VECTOR_SAFE<STD::string>obj; - $ intMain () $ { - -STD::stringSTR1 ("This is dream"); theSTD::stringSTR2 ("not covered?"); -Std::thread T1 (Std::bind (&vector_safe<std::string::p USH,&OBJ,STD::ref(STR1)));WuyiStd::thread T2 (Std::bind (&vector_safe<std::string>::GET_AND_POP,&OBJ,STD::ref(STR2))); the T1.join (); - T2.join (); Wustd::cout<<str2<<Std::endl; - return 0; About}
7.2 This is 0
C + + concurrency class member function invocation (Exercise 1)