//临界区对象
#include <WINDOWS.H>
#include <STDIO.H>
DWORD WINAPI myfun1(LPVOID lpParameter);
DWORD WINAPI myfun2(LPVOID lpParameter);
CRITICAL_SECTION m_Sec;
int a = 0;
int main()
{
InitializeCriticalSection(&m_Sec);//初始化临界区
HANDLE h1, h2;
h1 = ::CreateThread(NULL, 0, myfun1, NULL, 0, NULL);
printf("线程1开始运行!\r\n");
h2 = ::CreateThread(NULL, 0, myfun2, NULL, 0, NULL);
printf("线程2开始运行!\r\n");
::CloseHandle(h1);
::CloseHandle(h2);
//InitializeCriticalSection(&cs);//如果临界区的初始化在这里函数程序就会报错
::Sleep(10000);
DeleteCriticalSection(&m_Sec);
return 0;
}
DWORD WINAPI myfun1(LPVOID lpParameter)
{
while(1)
{
EnterCriticalSection(&m_Sec);
a++;
if(a<10000){
::Sleep(1000);
printf("线程1::%d\n", a);
LeaveCriticalSection(&m_Sec);
}else{
LeaveCriticalSection(&m_Sec);
break;
}
}
return 0;
}
DWORD WINAPI myfun2(LPVOID lpParameter)
{
while(1)
{
EnterCriticalSection(&m_Sec);
a++;
if(a<10000){
::Sleep(1000);
printf("线程2::%d\n", a);
LeaveCriticalSection(&m_Sec);
}else{
LeaveCriticalSection(&m_Sec);
break;
}
}
return 0;
}
事件对象(注意waitforsingleobject函数的用法)
#include<WINDOWS.H>
#include<STDIO.H>
DWORD WINAPI producerThread(LPVOID lpParament);
DWORD WINAPI customerThread(LPVOID lpParament);
HANDLE hEvent;
int n=0;
int main()
{
hEvent=::CreateEvent(NULL,FALSE,TRUE,NULL);
HANDLE pt,ct;
pt=::CreateThread(NULL,0,producerThread,NULL,0,NULL);
printf("生产者线程已经启动\r\n");
ct=::CreateThread(NULL,0,customerThread,NULL,0,NULL);
printf("消费者线程已经启动\r\n");
CloseHandle(pt);
CloseHandle(ct);
::Sleep(10000);
return 0;
}
DWORD WINAPI producerThread(LPVOID lpParament)
{
while (1)
{
::WaitForSingleObject(hEvent,INFINITE);
::ResetEvent(hEvent);
n++;
if (n<10000)
{
::Sleep(1000);
printf("生产者线程:%d\n",n);
::SetEvent(hEvent);
}else{
::SetEvent(hEvent);
break;
}
}
return 0;
}
DWORD WINAPI customerThread(LPVOID lpParament)
{
while (1)
{
::WaitForSingleObject(hEvent,INFINITE);
::ResetEvent(hEvent);
n++;
if (n<10000)
{
::Sleep(1000);
printf("消费者线程:%d\n",n);
::SetEvent(hEvent);
}else{
::SetEvent(hEvent);
break;
}
}
return 0;
}
互斥对象(注意waitforsingleobject函数的用法)
#include<WINDOWS.H>
#include<STDIO.H>
DWORD WINAPI producerThread(LPVOID lpParament);
DWORD WINAPI customerThread(LPVOID lpParament);
HANDLE hMutex;
int n=0;
int main()
{
hMutex=::CreateMutex(NULL,FALSE,NULL);
HANDLE pt,ct;
pt=::CreateThread(NULL,0,producerThread,NULL,0,NULL);
printf("生产者线程已经启动\r\n");
ct=::CreateThread(NULL,0,customerThread,NULL,0,NULL);
printf("消费者线程已经启动\r\n");
CloseHandle(pt);
CloseHandle(ct);
::Sleep(10000);
return 0;
}
DWORD WINAPI producerThread(LPVOID lpParament)
{
while (1)
{
::WaitForSingleObject(hMutex,INFINITE);
n++;
if (n<10000)
{
::Sleep(1000);
printf("生产者线程:%d\n",n);
::ReleaseMutex(hMutex);
}else{
::ReleaseMutex(hMutex);
break;
}
}
return 0;
}
DWORD WINAPI customerThread(LPVOID lpParament)
{
while (1)
{
::WaitForSingleObject(hMutex,INFINITE);
n++;
if (n<10000)
{
::Sleep(1000);
printf("消费者线程:%d\n",n);
::ReleaseMutex(hMutex);
}else{
::ReleaseMutex(hMutex);
break;
}
}
return 0;
}