hello, i want to allow one thread to print to a file then sleep for 2 seconds and give control to another thread, i wrote the code but it did n' t work,here is the code
Code:
#include "stdafx.h"
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <windows.h>
#include <time.h>
using namespace std;
HANDLE hEvent1 , hEvent2;
//thread function declaration
void WriteToFile1();
int flag =1;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD threadid[2],flag;
HANDLE h1[2];
hEvent1 = CreateEvent(NULL,TRUE,FALSE,NULL);
hEvent2 = CreateEvent(NULL,TRUE,FALSE,NULL);
SetEvent(hEvent1);
SetEvent(hEvent2);
h1[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WriteToFile1, NULL , CREATE_SUSPENDED, &threadid[0]);
h1[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WriteToFile1, NULL, CREATE_SUSPENDED, &threadid[1]);
::ResumeThread(h1[0]);
::ResumeThread(h1[1]);
//don't let this main thread die.
while(1)
{
flag=::WaitForMultipleObjects(2,h1,TRUE,INFINITE);
}
::CloseHandle(h1[0]);
::CloseHandle(h1[1]);
return 0;
}
// thread function definition
void WriteToFile1( )
{
while(1)
{
if(flag)
{
::WaitForSingleObject(hEvent2,INFINITE);
::ResetEvent(hEvent2);
struct tm *current;
time_t now;
time(&now);
//now contents current time
//convert current time to local time
current = localtime(&now);
//cout<<current->tm_hour<<current->tm_min<< current->tm_sec
//cout<<"i am inside the shared resource i.e a common file\n";
cout<<"current thread is:"<<::GetCurrentThreadId()<<"\tHH:MIN:SEC=\t"<<current->tm_hour<<":"<<current->tm_min<<":"<< current->tm_sec<<"\n";
fstream file;
file.open("c:\\common.txt", fstream::out | fstream::app);
file<<"thread_id = "<<::GetCurrentThreadId()<<"\tHH:MIN:SEC=\t";
file<<current->tm_hour<<":"<<current->tm_min<<":"<< current->tm_sec<<"\n";
file.close();
::SetEvent(hEvent1);
flag=0;
Sleep(2000);
}
else
{
::WaitForSingleObject(hEvent1,INFINITE);
::ResetEvent(hEvent1);
struct tm *current;
time_t now;
time(&now);
//now contents current time
//convert current time to local time
current = localtime(&now);
cout<<"current thread is:"<<::GetCurrentThreadId()<<"\tHH:MIN:SEC=\t"<<current->tm_hour<<":"<<current->tm_min<<":"<< current->tm_sec<<"\n";
fstream file;
file.open("c:\\common.txt", fstream::out | fstream::app);
file<<"thread_id = "<<::GetCurrentThreadId()<<"\tHH:MIN:SEC=\t";
file<<current->tm_hour<<":"<<current->tm_min<<":"<< current->tm_sec<<"\n";
file.close(); flag=1;
::SetEvent(hEvent2);
}
}
}
thanks puneet vyas