kevin55

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <windows.h>
#include <IOSTREAM.H>

//线程函数声明
DWORD WINAPI FuncProc1( LPVOID lpParameter//thread data
);
DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data
);

//int index = 0;
int tickets = 100;
HANDLE hMutex; //互斥对象

int main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL,//pointer to security attributes
0, //initial thread stack size
FuncProc1, // pointer to thread function
NULL, // argument for new thread
0, // creation flags
NULL); // pointer to receive thread ID

hThread2 = CreateThread(NULL,
0,
FuncProc2,
NULL,
0,
NULL);

CloseHandle(hThread1);
CloseHandle(hThread2);
/*while (index++ < 1000)
{
cout << "main thread is running" << endl;
}
*/

hMutex = CreateMutex(NULL,// pointer to security attributes
TRUE, // flag for initial ownership
"tickets" // pointer to mutex-object name
);

//可以利用上用"tickets"命名来判断只能运行一个实例
if (hMutex)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout << "Only one instance can run!" << endl;
return 0;
}
}

/* 这个地方线程互斥量已在主线程中,执行下面该语句名互斥量变为2,
则下面ReleaseMutex函数需要执行两次才能完全释放,让子线程去执行
*/
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);//此处需要释放主线程创建时得到的互斥量,否则子线程不执行
ReleaseMutex(hMutex);//
Sleep(4000);

return 0 ;
}

//线程函数定义
DWORD WINAPI FuncProc1(LPVOID lpParameter //thread data
)
{
/*while(index++ < 1000)
{
cout << "thread1 is running" << endl;
}
*/

while(TRUE)
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,//handle to object to wait for
INFINITE //time-out interval in milliseconds:INFINITE, the function's time-out interval never elapses.
);
if (tickets>0)
{
Sleep(10);
cout << "Thread1 sell tickets: " << tickets-- << endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}

return 0;
};

DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data
)
{
while(TRUE)
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(10);
cout << "Thread2 sell tickets: " << tickets-- << endl;
}
else
{
break;
}
ReleaseMutex(hMutex);
}

return 0;
}
posted on 2012-03-11 17:44  kernel_main  阅读(710)  评论(11编辑  收藏  举报