2009-02-17 09:45:57 +08:00
|
|
|
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
|
2008-05-02 22:19:38 +08:00
|
|
|
/*
|
|
|
|
This is a very simple example that illustrates the use of the
|
|
|
|
thread_function object from the dlib C++ Library.
|
|
|
|
|
|
|
|
The output of the programs should look like this:
|
|
|
|
|
|
|
|
45.6
|
|
|
|
9.999
|
|
|
|
I have no args!
|
2010-07-02 08:23:42 +08:00
|
|
|
val: 3
|
2008-05-02 22:19:38 +08:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
#include "dlib/threads.h"
|
2010-07-02 08:23:42 +08:00
|
|
|
#include "dlib/ref.h"
|
2008-05-02 22:19:38 +08:00
|
|
|
|
|
|
|
using namespace dlib;
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
void thread_1(double a)
|
|
|
|
{
|
|
|
|
cout << a << endl;
|
|
|
|
}
|
|
|
|
|
|
|
|
void thread_2 ()
|
|
|
|
{
|
|
|
|
cout << "I have no args!" << endl;
|
|
|
|
}
|
|
|
|
|
2010-07-02 08:23:42 +08:00
|
|
|
void thread_increment(double& a)
|
|
|
|
{
|
|
|
|
a += 1;
|
|
|
|
}
|
|
|
|
|
2008-05-02 22:19:38 +08:00
|
|
|
int main()
|
|
|
|
{
|
|
|
|
// create a thread that will call thread_1(45.6)
|
|
|
|
thread_function t1(thread_1,45.6);
|
|
|
|
// wait for the t1 thread to end
|
|
|
|
t1.wait();
|
|
|
|
|
|
|
|
|
|
|
|
// create a thread that will call thread_1(9.999)
|
|
|
|
thread_function t2(thread_1,9.999);
|
|
|
|
// wait for the t2 thread to end
|
|
|
|
t2.wait();
|
|
|
|
|
|
|
|
|
|
|
|
// create a thread that will call thread_2()
|
|
|
|
thread_function t3(thread_2);
|
|
|
|
|
|
|
|
|
2010-07-02 08:23:42 +08:00
|
|
|
// 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;
|
|
|
|
|
|
|
|
|
2008-05-02 22:19:38 +08:00
|
|
|
|
2010-07-02 08:32:43 +08:00
|
|
|
// At this point we will automatically wait for t3 to end because
|
|
|
|
// the destructor for thread_function objects always wait for their
|
|
|
|
// thread to terminate.
|
2008-05-02 22:19:38 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|