codice:
// generatore.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <winbase.h>
#include <time.h>
#include <string.h>
#define DIM 10
HANDLE DP,DV,PP,PV;
int pari[DIM],dispari[DIM],paripos=0,dispos=0;
CRITICAL_SECTION cs;
DWORD WINAPI cons(LPVOID nome)
{
printf("sto consumando");
int k=0;
while(1){
EnterCriticalSection(&cs);
if(!strcmp((char*)nome,"pari"))
{
//WaitForSingleObject(PP,INFINITE);
if (paripos==DIM-1)
{
for (k=0;k<DIM;k++)
printf("%d ",pari[k]);
}
paripos=0;
//ReleaseSemaphore(PV,1,NULL);
}
else if(!strcmp((char*)nome,"dispari"))
{
//WaitForSingleObject(DP,INFINITE);
if (dispos==DIM-1)
{
for (k=0;k<DIM;k++)
printf("%d ",dispari[k]);
}
dispos=0;
//ReleaseSemaphore(DV,1,NULL);
}
else
{
//LeaveCriticalSection(&cs);
return -1;
}
printf(" > ");
// LeaveCriticalSection(&cs);
return 0;
}
}
DWORD WINAPI prod(LPVOID n)
{
printf("sto producendo");
while(1){
int x;
x=rand()%100;
printf("%d ", x);
if (x%2==0)
{
//WaitForSingleObject(PV,INFINITE);
pari[paripos]=x;
paripos++;
//ReleaseSemaphore(DP,1,NULL);
}
else
{
//WaitForSingleObject(DV,INFINITE);
dispari[dispos]=x;
dispos++;
ReleaseSemaphore(DP,1,NULL);
}
}
return 0;
}
int main()
{
/* char *nome1 = "pari";
char *nome2 = "dispari"; */
srand((unsigned)time(NULL));
InitializeCriticalSection(&cs);
PP=CreateSemaphore(NULL,0,DIM,NULL);
PV=CreateSemaphore(NULL,DIM,DIM,NULL);
DP=CreateSemaphore(NULL,0,DIM,NULL);
DV=CreateSemaphore(NULL,DIM,DIM,NULL);
HANDLE t1=CreateThread(NULL,NULL,prod,NULL,NULL,NULL);
CreateThread(NULL,NULL,cons,nome1,NULL,NULL);
CreateThread(NULL,NULL,cons,nome2,NULL,NULL);
Sleep(10000);
CloseHandle(DP);
CloseHandle(DV);
CloseHandle(PP);
CloseHandle(PV);
/* for (int i=0; i<DIM; i++) printf("%d ", pari[i]);
printf("\n");
for (int i=0; i<DIM; i++) printf("%d ", dispari[i]); */
return 0;
}
Ciao e grazie per le risposte.