×

Loading...

let me answer question 1/2/3

本文发表在 rolia.net 枫下论坛Q1:
there 3 cpp file: for sharemem.dll
//sharemem.cpp
#include "windows.h"
#define BUFSIZE 256
#pragma data_seg(".shared")
volatile char internal_buffer[BUFSIZE]="";
volatile int status = 0;
#pragma data_seg()
#pragma comment(linker, "/SECTION:.shared,RWS")

__declspec(dllexport) bool writestr(char* str)
{
status=0;
if(strlen(str)>BUFSIZE)
return false;
strcpy((char*)internal_buffer,str);
status=1;
return true;
}


__declspec(dllexport) bool readstr(char* buf,unsigned len)
{
while(status<1)
Sleep(10);
if(strlen((const char*)internal_buffer)>=len)
return false;
strcpy(buf,(const char*)internal_buffer);
return true;
}

//p1.cpp for writer

#pragma comment(lib,"../sharemem")
__declspec(dllimport) bool writestr(char* str);
void main()
{
writestr("CooperNeff");
}

//p2.cpp for reader
#pragma comment(lib,"../sharemem")
#define BUFFERSIZE 256
__declspec(dllexport) bool readstr(char* buf,unsigned len);
#include "stdio.h"
void main()
{
char buf[BUFFERSIZE];

readstr(buf,BUFFERSIZE);
printf(buf);
}


Q2:
same as Q1,using share memory, each process wait the status
//processn.cpp
while(status!=n)
{
Sleep(10);
}
printf(myChar); //myChar is the nth in the string
status++;

Q3:
#include "stdio.h"
#include "windows.h"
#define QUEUESIZE 100
struct ValueQueue
{
int current;
int counter;
int value[QUEUESIZE];
CRITICAL_SECTION section;
int getvalue()
{
int result;
while(counter==0)
{
Sleep(10);
}
EnterCriticalSection(&section);
result=value[current];
current++;
current%=QUEUESIZE;
counter--;
LeaveCriticalSection(&section);
return result;
}
void putvalue(int i)
{
while(counter>=QUEUESIZE)
{
Sleep(10);
}
EnterCriticalSection(&section);
value[(current+counter)%QUEUESIZE]=i;
counter++;
LeaveCriticalSection(&section);
}
ValueQueue()
{
current=counter=0;
InitializeCriticalSection(&section);
}
~ValueQueue()
{
DeleteCriticalSection(&section);
}

};

DWORD WINAPI Thread1(LPVOID p)
{
ValueQueue* q=(ValueQueue*)p;
int n=0;
while(1)
{
n++;
if(!(n%50))
q->putvalue(n);

}
return 0;
}
DWORD WINAPI Thread2(LPVOID p)
{
ValueQueue* q=(ValueQueue*)p;
int n=0;
while(1)
{
int i=q->getvalue();
printf("%d\n",i);

}
return 0;
}

void main()
{
DWORD dummy;
HANDLE thread[2];
ValueQueue q;
thread[0]=CreateThread(0,1024*8,Thread2,(void*)&q,0,&dummy);
thread[1]=CreateThread(0,1024*8,Thread1,(void*)&q,0,&dummy);

while(1);
// WaitForMultipleObjects(2,thread,true,0);
CloseHandle(thread[0]);
CloseHandle(thread[1]);
}
I don't know why the WaitForMultipleObjects don't work, so I had to put a while(1); there. It's a shame.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Sign in and Reply Report