"vscode:/vscode.git/clone" did not exist on "cff821d8fe8b602d130a3418753df21b20cf02ce"
Commit b9f602e1 authored by Davis King's avatar Davis King
Browse files

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
parent 3ab9b590
...@@ -8,11 +8,13 @@ ...@@ -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 () ...@@ -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() ...@@ -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
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment