Ideas on implementing threads and cross process communication. - C
- by Jamie Keeling
Hello all!
I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice).
I will be using events for the following circumstances:
Process a sends data to process b, process b displays data
Process a closes, in turn closing process b
Process b closes a, in turn closing process a
I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occured.
I have already implemented a thread on the first process which currently creates the data to send to the second process and makes it available to the second process.
The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do.
Following is a small snippet of what I have so far in the producer application;
Rolling the dice and sending the data:
case IDM_FILE_ROLLDICE:
{
hDiceRoll = CreateThread(
NULL, // lpThreadAttributes (default)
0, // dwStackSize (default)
ThreadFunc(hMainWindow), // lpStartAddress
NULL, // lpParameter
0, // dwCreationFlags
&hDiceID // lpThreadId (returned by function)
);
}
break;
The data being sent to the other process:
DWORD WINAPI ThreadFunc(LPVOID passedHandle)
{
HANDLE hMainHandle = *((HANDLE*)passedHandle);
WCHAR buffer[256];
LPCTSTR pBuf;
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
struct diceData storage;
HANDLE hMapFile;
DWORD dw;
//Roll dice and store results in variable
storage = RollDice();
hMapFile = CreateFileMapping(
(HANDLE)0xFFFFFFFF, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
dw = GetLastError();
MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK);
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK);
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR)));
//_getch();
MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK);
UnmapViewOfFile(pBuf);
return 0;
}
I'd like to think I am at least on the right lines, although for some reason when the application finishes creating the thread it hits the
return DefWindowProc(hMainWindow, message, wParam, lParam);
it crashes saying there's no more source code for the current location.
I know there are certain ways to implement things but as I've mentioned I'm not sure if i'm doing this the right way, has anybody else tried to do the same thing?
Thanks!