From d0fdff0b6222bc5e4313ef529d80f75b6428a06b Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Sat, 5 May 2012 09:34:15 -0600 Subject: [PATCH] added two threading examples --- thread.cc | 18 ++++++++++++++++++ thread2.cc | 28 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 thread.cc create mode 100644 thread2.cc diff --git a/thread.cc b/thread.cc new file mode 100644 index 0000000..2362fec --- /dev/null +++ b/thread.cc @@ -0,0 +1,18 @@ +#include +#include + +//This function will be called from a thread + +void call_from_thread() { + std::cout << "Hello, World" << std::endl; +} + +int main() { + //Launch a thread + std::thread t1(call_from_thread); + + //Join the thread with the main thread + t1.join(); + + return 0; +} diff --git a/thread2.cc b/thread2.cc new file mode 100644 index 0000000..14ce632 --- /dev/null +++ b/thread2.cc @@ -0,0 +1,28 @@ +#include +#include + +static const int num_threads = 10; + +//This function will be called from a thread + +void call_from_thread(int tid) { + std::cout << "Launched by thread " << tid << std::endl; +} + +int main() { + std::thread t[num_threads]; + + //Launch a group of threads + for (int i = 0; i < num_threads; ++i) { + t[i] = std::thread(call_from_thread, i); + } + + std::cout << "Launched from the main\n"; + + //Join the threads with the main thread + for (int i = 0; i < num_threads; ++i) { + t[i].join(); + } + + return 0; +}