
[英]C++ making a separate thread in the Windows API, program terminates?
[英]making restaurent simulation program with C++, thread, Semaphore
我的家庭作业正在制作餐厅模拟程序。
30个座位同时,有30人可以吃饭。 午餐时间,大约有200位客人吃饭。 午餐开始于11:30,结束于2:00。 假设进餐时间为10分钟至50分钟。
使用事件,信号量,计时器,关键部分功能。 使用时间功能。 打印每个客人进来的时间,吃饭的时间以及饭后离开的时间
额外分数)
编码时请参考我的代码。
请给我解决方案。 我也想发表评论。
谢谢。
我的代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <tchar.h>
#define NUM_OF_CUSTOMER 50
#define RANGE_MIN 10
#define RANGE_MAX (30 - RANGE_MIN)
#define TABLE_CNT 10
HANDLE hSemaphore;
DWORD randTimeArr[50];
void TakeMeal(DWORD time)
{
WaitForSingleObject(hSemaphore, INFINITE);
_tprintf( _T("Enter Customer %d~ \n"), GetCurrentThreadId());
_tprintf(_T("Customer %d having launch~ \n"), GetCurrentThreadId());
Sleep(1000 * time); //eating simulation.
ReleaseSemaphore(hSemaphore, 1, NULL);
_tprintf( _T("Out Customer %d~ \n\n"), GetCurrentThreadId());
}
unsigned int WINAPI ThreadProc( LPVOID lpParam )
{
TakeMeal((DWORD)lpParam);
return 0;
}
int _tmain(int argc, TCHAR* argv[])
{
DWORD dwThreadIDs[NUM_OF_CUSTOMER];
HANDLE hThreads[NUM_OF_CUSTOMER];
srand( (unsigned)time( NULL ) ); // random function seed
// Generate a total of 50 random values to pass to the thread.
for(int i=0; i<NUM_OF_CUSTOMER ;i++)
{
randTimeArr[i] = (DWORD) (
((double)rand() / (double)RAND_MAX) * RANGE_MAX + RANGE_MIN
);
}
//Create Semaphore.
hSemaphore = CreateSemaphore (
NULL, // default secure manager
TABLE_CNT, // Semaphore Initial value
TABLE_CNT, // Semaphore Max value
NULL // unnamed Semaphore.
);
if (hSemaphore == NULL)
{
_tprintf(_T("CreateSemaphore error: %d\n"), GetLastError());
}
// Customer thread
for(int i=0; i<NUM_OF_CUSTOMER; i++)
{
hThreads[i] = (HANDLE)
_beginthreadex (
NULL,
0,
ThreadProc,
(void*)randTimeArr[i],
CREATE_SUSPENDED,
(unsigned *)&dwThreadIDs[i]
);
if(hThreads[i] == NULL)
{
_tprintf(_T("Thread creation fault! \n"));
return -1;
}
}
for(int i=0; i<NUM_OF_CUSTOMER; i++)
{
ResumeThread(hThreads[i]);
}
WaitForMultipleObjects(NUM_OF_CUSTOMER, hThreads, TRUE, INFINITE);
_tprintf(_T("----END-----------\n"));
for(int i=0; i<NUM_OF_CUSTOMER; i++)
{
CloseHandle(hThreads[i]);
}
CloseHandle(hSemaphore);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.