Click to See Complete Forum and Search --> : thread synchronisation


javanewuser
March 9th, 2011, 03:45 AM
Can any one suggest how to proceed with this.

Actually on click of volume button volume should be increased till 100 when end button is clicked volume process should be stopped. this is my proj.

Can anyy one share the code for the below thing so that i can implement same in myy proj
On clicking on print button it should start printing even numbers on the console when the end button is clicked it should stop printing.
When print button is clicked end button click is not recognised until the print process is completed

Igor Vartanov
March 12th, 2011, 12:48 AM
Here you can find a very basic sample for threads interaction. Please ask any questions you have about it.

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>

HANDLE hPrintEvent = NULL;
HANDLE hStopEvent = NULL;

const DWORD PRINT_TIMEOUT = 200; // milliseconds, the main print interval

DWORD WINAPI ThreadProc(LPVOID pVoid)
{
__int64 counter = 0;

_tprintf(TEXT("\n> "));

while (1)
{
DWORD waitRes = WaitForSingleObject(hStopEvent, PRINT_TIMEOUT);

switch (waitRes)
{
case WAIT_ABANDONED:
case WAIT_FAILED:
_tprintf(TEXT("\nWaiting failed. Quit.\n"));
return 0;

case WAIT_OBJECT_0:
_tprintf(TEXT("\nStop signal caught. Quit.\n"));
return 0;

case WAIT_TIMEOUT:
waitRes = WaitForSingleObject(hPrintEvent, 0);
if (WAIT_OBJECT_0 == waitRes)
{
// print allowed
++counter;
_tprintf(TEXT("\r \r> %I64d"), counter);
}
break;
}
}

return 0;
}

int _tmain()
{
hPrintEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

DWORD threadId;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, &threadId);
if (hThread)
{
_tprintf(TEXT("Press p to resume printing, s to suspend it, and q to quit.\n> "));

while (1)
{
int ch = getch();
if ('p' == ch)
SetEvent(hPrintEvent);
else if ('s' == ch)
ResetEvent(hPrintEvent);
else if ('q' == ch)
{
SetEvent(hStopEvent);
break;
}
}

WaitForSingleObject(hThread, INFINITE);
}

CloseHandle(hPrintEvent);
CloseHandle(hStopEvent);
CloseHandle(hThread);

return 0;
}