Updated this example so that it shows how to pass arguments to threads

by reference using the ref() function.

--HG--
extra : convert_revision : svn%3Afdd8eb12-d10e-0410-9acb-85c331704f74/trunk%403712
This commit is contained in:
Davis King 2010-07-02 00:23:42 +00:00
parent 3ab9b590c0
commit b9f602e1b6

View File

@ -8,11 +8,13 @@
45.6 45.6
9.999 9.999
I have no args! I have no args!
val: 3
*/ */
#include <iostream> #include <iostream>
#include "dlib/threads.h" #include "dlib/threads.h"
#include "dlib/ref.h"
using namespace dlib; using namespace dlib;
using namespace std; using namespace std;
@ -27,6 +29,11 @@ void thread_2 ()
cout << "I have no args!" << endl; cout << "I have no args!" << endl;
} }
void thread_increment(double& a)
{
a += 1;
}
int main() int main()
{ {
// create a thread that will call thread_1(45.6) // create a thread that will call thread_1(45.6)
@ -45,6 +52,15 @@ int main()
thread_function t3(thread_2); thread_function t3(thread_2);
// Note that we can also use the ref() function to pass a variable
// to a thread by reference. For example, the thread below adds
// one to val.
double val = 2;
thread_function t4(thread_increment, ref(val));
t4.wait(); // wait for t4 to finish before printing val.
cout << "val: " << val << endl;
// we will wait for t3 to end here because the destructor for // we will wait for t3 to end here because the destructor for
// thread_function objects always waits for their thread to end // thread_function objects always waits for their thread to end