Your example makes no sense. Threads are used for lengthy operations or to suspend when waiting for events. But you want to perform a short operation (vector push_back) multiple times inside a loop.
The answer to your question is quite simple:
std::thread th(&Schedule::add, &obj, "NAME");
th.detach();
But this would require locking within your
add()
function where
mut
is a
std::mutex
class member:
void add(std::string name)
{
std::unique_lock<std::mutex> lk(mut);
name_list.push_back(name);
}
So a better solution would be adding a function to your Schedule class that creates a thread which performs the operation:
void add_threaded(std::string name)
{
std::thread th(&Schedule::add, this, name);
th.detach();
}
But these solutions will probably consume more time than the not threaded code.
The above examples create threads with a non-static member function. For those the
std::thread
constructor requires the address of the member function and a pointer to the class followed by optional arguments.
Surprinsingly there are not so many
std::thread
tutorials covering class member functions in the web as expected. So it should bee not too difficult to find one or more useful ones.
Some examples:
Multithreading in C++0x part 1: Starting Threads[
^]
C++11: std::threads managed by a designated class | Rafał Cieślak's blog[
^]
A brand new one here at CP that covers message handling which may be more appropriate for you (signaling a thread in the
Schedule
class to add items):
C++ std::thread Event Loop with Message Queue and Timer[
^]