/* example to demonstrate threads in Win32
 * main program + two threads
 * parameter passing to thread writer2
 */


/* If you are using the Visual C++ development environment, select the 
 * Multi-Threaded runtime library in the compiler Project Settings 
 * dialog box - see C/C++, Code Generation.
 */


/* by Albrecht Schmidt, Lancaster University - Oct 2001
 * http://www.comp.lancs.ac.uk/~albrecht 
 * Albrecht@comp.lancs.ac.uk
 */

#include "stdafx.h"
#include <windows.h>
#include <process.h>

// the parameter passed to a thread
typedef struct
{
	    int loops;
		int duration;
		char txt[255];
}
PARAMS, *PPARAMS;

// void pointer - standard parameter
typedef void *PVOID;

void writer1 (PVOID pvoid); // no parameter
void writer2 (PVOID pvoid); // 

// main routine starting the threads
int main(int argc, char* argv[])
{
	int i;
	static PARAMS a_para;

	printf("Start Main Prog\n");
	
	// set the parameters
	a_para.loops = 5;
	a_para.duration = 2000;
	strcpy(a_para.txt, "Hi there ...");

	PVOID pvoidv = NULL;

	// start thread without parameter
	_beginthread(writer1, 0, pvoidv);
	// start another thread with parameters
	_beginthread(writer2, 0, &a_para);
	
	// do something in the main prog
	for (i=1;i<5;i++) {
		printf("Main: %i\n", i);
		Sleep(1000);
	}

	printf("Terminate main!\n");
	_endthread(); 
	return 0;
}

// thread - taking no parameters and does a fixed output
void writer1 (PVOID pvoid)
{
	int i;

	printf("Startup writer1!\n");
	
	// do the output
	for (i=1;i<10;i++) {
		printf("Writer1: %i\n", i);
		Sleep(500);
	}

	printf("Terminate writer1!\n");
	
	_endthread(); 
}

// thread taking parameters
void writer2 (PVOID pvoid)
{
	int i;

	int dur;
	int iter;
	char localtxt[255];

	printf("Startup writer2\n");

	// cast the parameters
	PPARAMS para;
	para = (PPARAMS) pvoid;
    // read the parameters
	dur = para->duration;
	iter = para->loops;
	strcpy(localtxt, para->txt);	
	
	for (i=0;i<iter;i++) {
		printf("Writer2: %s %i\n",localtxt, i);
		Sleep(dur);
	}

	printf("Terminate writer2!\n");
	
	_endthread(); 
}
