//////////////////////////////////////////////////////////////////////////////////////
//
// ACE example code.
// This code spawns a thread that prints to the screen once a second until it is
// told to stop.
//
// Author: Yuval Baror (http://yuval.bar-or.org)
//
//////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <ace/Thread_Manager.h>
#include <ace/Thread.h>
#include <ace/OS.h>

using namespace std;

// As long as keepWorking is true, the spawned thread will keep printing to the screen.
static bool keepWorking = true;

// This is the function that will be running in the spawned thread.
void* threadFunc(void *arg)
{
	ACE_OS::sleep(ACE_Time_Value(0, 5000)); // Add an initial delay of half a second
	while(keepWorking)
	{
		cout << "Thread - yawn. That was a nice nap. I think I'll sleep a bit more." << endl;
		ACE_OS::sleep(1);
	}

	cout << "Thread - I'm done working for you!" << endl;
	return NULL;
}

// Main entry point
int main(int argc, char **argv)
{
	ACE_Thread_Manager threadManager;
	ACE_thread_t threadId;
	
	// Create one thread running the thread function
	if (threadManager.spawn((ACE_THR_FUNC)threadFunc, NULL, 0, &threadId) == -1)
	{
		cerr << "Error spawning thread" << endl;
		return -1;
	}

	cout << "Main - thread spawned with thread id " << threadId << "." << endl;

	// Sleep for 5 seconds and let the thread do some work.
	ACE_OS::sleep(5);

	// Now stop the thread and wait for it to exit.
	keepWorking = false;
	cout << "Main - end of work shift. Waiting for all threads to exit." << endl;
	threadManager.wait();

	cout << "Main - done." << endl;
	return 0;
}

