#include<stdio.h>
#include<process.h>
#include<windows.h>
#include<stdlib.h>
int arr[2]={23,4};
int x=0;
HANDLE va;
HANDLE vb;
HANDLE mutex;
unsigned int _stdcall fun1(void *p)
{
int threadnum=*(int *)p;
int flag=1;
while(flag)
{
WaitForSingleObject(vb,INFINITE);
Sleep(50);
x=arr[0]+arr[1];
flag=0;
printf("thread=%d,x1=%d\n",threadnum,x);
SetEvent(va);
}
return 0;
}
unsigned int _stdcall fun2(void *p)
{
int threadnum=*(int *)p;
int flag=1;
while(flag)
{
WaitForSingleObject(va,INFINITE);
Sleep(50);
//ReleaseMutex(mutex);
x+=2;
flag=0;
printf("thread=%d,x2=%d\n",threadnum,x);
SetEvent(va);
SetEvent(vb);
}
return 0;
}
int main()
{
HANDLE h[21];
int i=0;
int j=1;
va=CreateEvent(NULL,FALSE,0,NULL);
vb=CreateEvent(NULL,FALSE,1,NULL);
mutex=CreateMutex(NULL,0,NULL);
h[i]=(HANDLE)_beginthreadex(NULL,0,fun1,&i,0,NULL);
for(;j<21;++j)
{
h[j]=(HANDLE)_beginthreadex(NULL,0,fun2,&j,0,NULL);
// WaitForSingleObject(mutex,INFINITE);
}
WaitForMultipleObjects(21,h,TRUE,INFINITE);
CloseHandle(va);
CloseHandle(vb);
CloseHandle(mutex);
system("pause");
return 0;
}
#include<process.h>
#include<windows.h>
#include<stdlib.h>
int arr[2]={23,4};
int x=0;
HANDLE va;
HANDLE vb;
HANDLE mutex;
unsigned int _stdcall fun1(void *p)
{
int threadnum=*(int *)p;
int flag=1;
while(flag)
{
WaitForSingleObject(vb,INFINITE);
Sleep(50);
x=arr[0]+arr[1];
flag=0;
printf("thread=%d,x1=%d\n",threadnum,x);
SetEvent(va);
}
return 0;
}
unsigned int _stdcall fun2(void *p)
{
int threadnum=*(int *)p;
int flag=1;
while(flag)
{
WaitForSingleObject(va,INFINITE);
Sleep(50);
//ReleaseMutex(mutex);
x+=2;
flag=0;
printf("thread=%d,x2=%d\n",threadnum,x);
SetEvent(va);
SetEvent(vb);
}
return 0;
}
int main()
{
HANDLE h[21];
int i=0;
int j=1;
va=CreateEvent(NULL,FALSE,0,NULL);
vb=CreateEvent(NULL,FALSE,1,NULL);
mutex=CreateMutex(NULL,0,NULL);
h[i]=(HANDLE)_beginthreadex(NULL,0,fun1,&i,0,NULL);
for(;j<21;++j)
{
h[j]=(HANDLE)_beginthreadex(NULL,0,fun2,&j,0,NULL);
// WaitForSingleObject(mutex,INFINITE);
}
WaitForMultipleObjects(21,h,TRUE,INFINITE);
CloseHandle(va);
CloseHandle(vb);
CloseHandle(mutex);
system("pause");
return 0;
}