int main()
{
    HANDLE hThrd;
    DWORD exitCode = 0;
    DWORD threadId;
    
    MTVERIFY( hThrd = CreateThread(NULL,
        0,
        ThreadFunc,
        (LPVOID)1,
        0,
        &threadId )
    );
    if (hThrd)
        printf("Thread launched\n");

    MTVERIFY( CloseHandle(hThrd) );

    for(;;)
    {
        BOOL rc;
        MTVERIFY( rc = GetExitCodeThread(hThrd, &exitCode) );
	if (rc || exitCode != STILL_ACTIVE )
            break;
    }

    printf("Thread returned %d\n", exitCode);

    return EXIT_SUCCESS;
}
Beispiel #2
0
int main()
{
    HANDLE hThrd;
    DWORD exitCode = 0;
    DWORD threadId;

    puts("Waiting...");

    MTVERIFY( hThrd = CreateThread(NULL,
        0,
        ThreadFunc,
        (LPVOID)1,
        0,
        &threadId )
    );
    /* This busy loop chews up lots of CPU time */
    for (;;)
    {
        GetExitCodeThread(hThrd, &exitCode);
        if ( exitCode != STILL_ACTIVE )
            break;
    }

    printf("Finished.\n");

    MTVERIFY( CloseHandle(hThrd) );

    return EXIT_SUCCESS;
}
Beispiel #3
0
void CConfigManager::ReadRouteTCPListen(int *pPorts, unsigned long *pIP)
{
	char BuffIP[16];

	*pPorts = GetPrivateProfileIntA("TCP_SOCKET", "LISTEN_LOCAL_PORT", -1, "Config\\PostofficeRoute\\PostofficeRoute.ini");
	GetPrivateProfileStringA("TCP_SOCKET", "LISTEN_LOCAL_IP", "255.255.255.255", BuffIP, 16, "Config\\PostofficeRoute\\PostofficeRoute.ini");

	*pIP = inet_addr(BuffIP);
	unsigned long L =inet_addr("255.255.255.255");

	MTVERIFY( -1!=*pPorts );
	MTVERIFY( L!=*pIP );

}
int main(VOID) 
{ 
	HINSTANCE hinstLib; 
    HANDLE hThrd;
    DWORD threadId;
 
    printf("\tCalling LoadLibrary()\n");

    // Get a handle to the DLL module.
    hinstLib = LoadLibrary("SmallDll"); 
 
    // If the handle is valid, try to get the function address.
 
    if (hinstLib == NULL) 
	{
		fprintf(stderr, "LoadLibrary failed. Could not find SmallDll.DLL\n");
		return 1;
	}

	// Find the entry point into the library. It is a
	// C++ function, so we use the decorated name.
    pTheFunction = (THEFUNCTION) GetProcAddress(hinstLib, "?TheFunction@@YAHXZ");
	if (pTheFunction == NULL)
	{
		fprintf(stderr, "\nGetProcAddress failed. There is probably a\n");
		fprintf(stderr, "calling convention or parameter mismatch.\n\n");
		return 1;
	}

	hThrd = CreateThread(NULL,
	    0,
	    ThreadFunc,
	    NULL,
	    0,
	    &threadId );
	MTVERIFY(hThrd != NULL);
	if (hThrd)
	    printf("\tThread launched\n");
 
	MTVERIFY( WaitForSingleObject(hThrd, INFINITE) == WAIT_OBJECT_0 );
	MTVERIFY( CloseHandle(hThrd) );

	// Free the DLL module.
	printf("\tCalling FreeLibrary()\n");
    FreeLibrary(hinstLib);

    return 0;
}
Beispiel #5
0
void PrintDlg_OnPaint( HWND hwnd )
{
    PAINTSTRUCT paint;
    HWND hwndCtrl;
	HDC hdc;
    HDC hDcMem;
    HBITMAP bmpOld;
    RECT rect;
    POINT point;

	if (!gbmpDisplay)
		return;

    hwndCtrl = GetDlgItem(hwnd, IDC_OUTPUT);

    hdc = BeginPaint(hwnd, &paint);

    GetWindowRect(hwndCtrl, &rect);
    point = *((POINT *)&rect);
    ScreenToClient(hwnd, &point);

    hDcMem = CreateCompatibleDC(NULL);
    bmpOld = SelectObject(hDcMem, gbmpDisplay);

    // Copy bitmap to screen
    MTVERIFY( BitBlt(hdc, point.x+10, point.y+40,
        gDisplayRect.right-gDisplayRect.left, gDisplayRect.bottom-gDisplayRect.top,
        hDcMem, iHeight, 0, SRCCOPY) );

    SelectObject(hDcMem, bmpOld);
    DeleteDC(hDcMem);

    EndPaint(hwnd, &paint);
}
Beispiel #6
0
int _tmain(int argc, _TCHAR* argv[])
{	
	int i, nResult;
	
	WSADATA WsaData;
	nResult = WSAStartup(MAKEWORD(2,2),&WsaData);
	MTVERIFY( 0==nResult );

	/*
		这里是控制和邮局路由的更新线程
	*/
	CServerRoute ServerRoute;

	ServerRoute.Init();
	ServerRoute.Start();


	/*
		这里是控制完成端口的
	*/
	int nCPUNumberOf = GetCPUNumberOf()*2;

	CServerBinPlay ServerBinPlay;
	ServerBinPlay.Init( nCPUNumberOf );

	for(i=0; i<nCPUNumberOf; ++i)
	{
		ServerBinPlay.Start(i);
	}

	ServerBinPlay.StartAccept();

	//
	//Clean
	GetQuitCommand();
	printf("Clean start:\n");

	if( WAIT_TIMEOUT==ServerRoute.ServerRouteThread.End() )
	{
		printf("WAIT_TIMEOUT==ServerRouteThread.End():%d\n", GetLastError());		
	}

	if( WAIT_TIMEOUT==ServerBinPlay.ServerBinPlayThreadAccept.End() )
	{
		printf("WAIT_TIMEOUT==ServerBinPlayAccept.End():%d\n", GetLastError());		
	}

	for(i=0; i<nCPUNumberOf; ++i)
	{
		if( WAIT_TIMEOUT==ServerBinPlay.pServerBinPlayThread[i].End() )
		{
			printf("WAIT_TIMEOUT==ServerBinPlay.pServerBinPlayThread.End():%d\n", GetLastError());			
		}
	}

	WSACleanup();
        
	return 0;
}
Beispiel #7
0
void CConfigManager::ReadRouteUDPListen(int nIndex, int *pPorts, unsigned long *pIP)
{
	char BuffIP[16];
	char PortValueName[64];
	char IPValueName[64];

	sprintf(PortValueName, "%s_%d", "LISTEN_LOCAL_PORT", nIndex);
	sprintf(IPValueName, "%s_%d", "LISTEN_LOCAL_IP", nIndex);

	*pPorts = GetPrivateProfileIntA("UDP_SOCKET", PortValueName, -1, "Config\\PostofficeRoute\\PostofficeRoute.ini");
	GetPrivateProfileStringA("UDP_SOCKET", IPValueName, "255.255.255.255", BuffIP, 16, "Config\\PostofficeRoute\\PostofficeRoute.ini");
	
	*pIP = inet_addr(BuffIP);
	unsigned long L = inet_addr("255.255.255.255");

	MTVERIFY( -1!=*pPorts );
	MTVERIFY( L!=*pIP );
}
Beispiel #8
0
int main()
{
    HANDLE hThrd;
    DWORD exitCode = 0;
    DWORD threadId;
    DWORD begin;
    DWORD elapsed;

    puts("Timing normal function call...");
    begin = GetTickCount();
    ThreadFunc(0);
    elapsed = GetTickCount()-begin;
    printf("Function call took: %d.%.03d seconds\n\n", elapsed/1000, elapsed%1000);
    
    puts("Timing thread + busy loop...");
    begin = GetTickCount();

    MTVERIFY( hThrd = CreateThread(NULL,
        0,
        ThreadFunc,
        (LPVOID)1,
        0,
        &threadId )
    );

    /* This busy loop chews up lots of CPU time */
    for (;;)
    {
        GetExitCodeThread(hThrd, &exitCode);
        if ( exitCode != STILL_ACTIVE )
            break;
    }

    elapsed = GetTickCount()-begin;
    printf("Thread + busy loop took: %d.%.03d seconds\n",
                elapsed/1000, elapsed%1000);

    MTVERIFY( CloseHandle(hThrd) );

    return EXIT_SUCCESS;
}
Beispiel #9
0
///////////////////////////////////////////////////////////
//
//		StartThreads
//
// Create the threads that will be waiting on the 
// event object. Each thread is passed its number.
//
void StartThreads()
{
	int i;
	for (i=0; i<MAX_THREADS; i++)
	{
		MTVERIFY( gThreads[i] = CreateThread(NULL,
			0,
			ThreadProc,
			(LPVOID)i,
			0,
			&threadId ) );
	}
}
Beispiel #10
0
DWORD WINAPI SearchProc( void *arg )
{
    WIN32_FIND_DATA *lpFindData = (WIN32_FIND_DATA *)arg;
    char buf[1024];
    HANDLE hFile;
    DWORD dummy;

    hFile = CreateFile(lpFindData->cFileName,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        OPEN_EXISTING,
                        FILE_FLAG_SEQUENTIAL_SCAN,
                        NULL
                    );
    if (!hFile)
        return 1;   /* Silently ignore problem files */

    while (GetLine(hFile, buf, sizeof(buf)))
    {
        /* Inefficient search strategy, but it's easy */
        if (strstr(buf, szSearchFor))
        {
            /* Make sure that this thread is the
             * only one writing to this handle */
            EnterCriticalSection( &ScreenCritical );

            WriteFile( hConsoleOut,
                lpFindData->cFileName,
                strlen(lpFindData->cFileName),
                &dummy,
                FALSE );
            WriteFile( hConsoleOut,
                ": ", 2, &dummy, FALSE );
            WriteFile( hConsoleOut,
                buf, strlen(buf), &dummy, FALSE );
            WriteFile( hConsoleOut,
                "\r\n", 2, &dummy, FALSE );

            LeaveCriticalSection( &ScreenCritical );
        }
    }

    CloseHandle(hFile);
    HeapFree( GetProcessHeap(), 0, lpFindData);

    MTVERIFY( ReleaseSemaphore( hThreadLimitSemaphore,
                                    1,
                                    NULL ) );
}
Beispiel #11
0
///////////////////////////////////////////////////////////
//
//		ThreadProc
//
// This is the entry point for new threads. Make an entry
// in the log that this thread is about to wait, then go to
// sleep waiting on the event object. When we wake up,
// tell the user and go back to sleep.
//
// We Sleep briefly after the event is signaled to prevent
// the app from generating thousands of wakeup messages with
// with manual events.
//
DWORD WINAPI ThreadProc(LPVOID n)
{
	char buf[80];

	for (;;)
	{
		wsprintf(buf, "Thread #%d calling WaitForSingleObject", n);
		AddToList(buf);
		Sleep(100);
		MTVERIFY( WaitForSingleObject(hEventObject, INFINITE) != WAIT_FAILED );
		wsprintf(buf, "Thread #%d woke up", n);
		AddToList(buf);
	}
	return 0;
}
BOOL CShareMemApp::InitInstance()
{
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

    // Create a mutex with initial ownership. If it already
    // exists, we will block until it is available.
    ghDataLock = ::CreateMutex(NULL, TRUE, "ShareMem Data Mutex");
    MTVERIFY( ghDataLock != NULL );

    HANDLE hFileMapping;

    hFileMapping = ::CreateFileMapping(
                        (HANDLE)0xFFFFFFFF,  // File handle
                        NULL,                // Security attributes
                        PAGE_READWRITE,      // Protection
                        0,                   // Size - high 32 bits
                        1<<16,               // Size - low 32 bits
                        "ShareMem Sample App Data Block"); // Name
    MTVERIFY( hFileMapping != NULL );
    DWORD dwMapErr = GetLastError();

    gpSharedBlock = (SharedBlock*) ::MapViewOfFile(
                        hFileMapping,        // File mapping object
                        FILE_MAP_ALL_ACCESS, // Read/Write
                        0,                  // Offset - high 32 bits
                        0,                  // Offset - low 32 bits
                        0);                 // Map the whole thing
    MTVERIFY( gpSharedBlock != NULL );

    // Only initialize shared memory if we actually created.
    if (dwMapErr != ERROR_ALREADY_EXISTS)
        gpSharedBlock->m_nStringCount = 0;

    ::ReleaseMutex(ghDataLock);

    CShareMemDlg dlg;
    m_pMainWnd = &dlg;
    int nResponse = dlg.DoModal();

    MTVERIFY( ::UnmapViewOfFile(gpSharedBlock) );
    MTVERIFY( ::CloseHandle(hFileMapping) );
    MTVERIFY( ::CloseHandle(ghDataLock) );

    // Since the dialog has been closed, return FALSE so that we exit the
    // application, rather than start the application's message pump.
	return FALSE;
}
Beispiel #13
0
bool CThreadPool::ExecuteTask(IThread * ExecutionTarget, const char* ThreadName)
{
	ThreadCtrl *pTC= new ThreadCtrl;

	pTC->pIThread = ExecutionTarget;
	strncpy(pTC->ThreadName, ThreadName, 16);
	pTC->Thread.m_dwStartTime = CTime::GetMilli();

	pTC->Thread.m_hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, pTC, 0, &pTC->Thread.m_uThread);	
	MTVERIFY( 0!= pTC->Thread.m_hThread);

	m_ThreadSet.push_back(pTC);

	return true;
}
Beispiel #14
0
//
// Asks user which printer to use, then creates
// background printing thread.
//
void PrintText(HWND hwndParent, char *pszText)
{
    ThreadPrintInfo *pInfo;
    HANDLE hThread;
    DWORD dwThreadId;
    int result;
    DOCINFO docInfo;

    PRINTDLG dlgPrint;

    // Put up Common Dialog for Printing and get hDC.
    memset(&dlgPrint, 0, sizeof(PRINTDLG));
    dlgPrint.lStructSize = sizeof(PRINTDLG);
    dlgPrint.hwndOwner = hwndParent;
    dlgPrint.Flags = PD_ALLPAGES | PD_USEDEVMODECOPIES
           | PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
    dlgPrint.hInstance = hInst;
    if (!PrintDlg(&dlgPrint))
        return;

    // Initialize Printer device
    docInfo.cbSize = sizeof(DOCINFO);
    docInfo.lpszDocName = "Background Printing Example";
    docInfo.lpszOutput = NULL;
    docInfo.lpszDatatype = NULL;
    docInfo.fwType = 0;
    result = StartDoc(dlgPrint.hDC, &docInfo);
    result = StartPage(dlgPrint.hDC);

    pInfo = HeapAlloc(GetProcessHeap(),
                      HEAP_ZERO_MEMORY,
                      sizeof(ThreadPrintInfo));
    pInfo->hDlg = hwndParent;
    pInfo->hWndParent = hwndParent;
    pInfo->hDc = dlgPrint.hDC;
    pInfo->bPrint = TRUE;
    strcpy(pInfo->szText, pszText);

    MTVERIFY( hThread = CreateThread(NULL, 0,
        BackgroundPrintThread, (LPVOID)pInfo,
        0, &dwThreadId ));

	// keep track of all background printing threads
    gPrintJobs[gNumPrinting++] = hThread;
}
Beispiel #15
0
//
// Shows output on the dialog box.
//
void PrintToDisplay(HWND hwndParent, char *pszText)
{
    ThreadPrintInfo *pInfo;
    DWORD dwThreadId;
    HANDLE hThread;

    pInfo = HeapAlloc(GetProcessHeap(),
                      HEAP_ZERO_MEMORY,
                      sizeof(ThreadPrintInfo));
    pInfo->hDlg = hwndParent;
    pInfo->hWndParent = GetDlgItem(hwndParent, IDC_OUTPUT);
	pInfo->hDc = GetDC(pInfo->hWndParent);
    pInfo->bPrint = FALSE;
    strcpy(pInfo->szText, pszText);

    MTVERIFY( hThread = CreateThread(NULL, 0,
                                     BackgroundPrintThread,
                                     (LPVOID)pInfo,
                                     0, &dwThreadId ));

	// keep track of all background printing threads
    gPrintJobs[gNumPrinting++] = hThread;
}
Beispiel #16
0
void CConfigRead::Read_CNetAccept(USHORT *pPort)
{
	*pPort = GetPrivateProfileIntA("SOCKET", "LOCAL_GAMESERVER_PORT", 1, "Config\\PhonebookServer.ini");

	MTVERIFY( 1!=*pPort );	
}
Beispiel #17
0
//
//public
void CBinServerPlayThread::Start(void *pArguments)
{
	hThreadSelf = (HANDLE)_beginthreadex(NULL, 0, ThreadStartAddr, pArguments, 0, &idThreadSelf);
	MTVERIFY( 0!=hThreadSelf );	
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    WIN32_FIND_DATA *lpFindData;
    HANDLE hFindFile;
    HANDLE hThread;
    DWORD dummy;
    int i;

    hConsoleOut = GetStdHandle( STD_OUTPUT_HANDLE );

    if (argc != 2)
    {
        char errbuf[512];
        wsprintf(errbuf,
            "Usage: %s <search-string>\n",
            argv[0]);
        WriteFile( hConsoleOut,
            errbuf,
            strlen(errbuf),
            &dummy,
            FALSE );
        return EXIT_FAILURE;
    }

    /* Put search string where everyone can see it */
    strcpy(szSearchFor, argv[1]);

    /* Allocate a find buffer to be handed
     * to the first thread */
    lpFindData = HeapAlloc( GetProcessHeap(),
            HEAP_ZERO_MEMORY,
            sizeof(WIN32_FIND_DATA) );

    /* Semaphore prevents too many threads from running */
    MTVERIFY( hThreadLimitSemaphore = CreateSemaphore(
            NULL,   /* Security */
            MAX_THREADS,    /* Make all of them available */
            MAX_THREADS,    /* Allow a total of MAX_THREADS */
            NULL )          /* Unnamed */
         );

    InitializeCriticalSection(&ScreenCritical);

    hFindFile = FindFirstFile( "*.c", lpFindData );

    if (hFindFile == INVALID_HANDLE_VALUE)
        return EXIT_FAILURE;

    do {
        WaitForSingleObject( hThreadLimitSemaphore,
                        INFINITE );

        MTVERIFY( hThread = CreateThread(NULL,
                        0,
                        SearchProc,
                        lpFindData, // arglist
                        0,
                        &dummy )
         );

        MTVERIFY( CloseHandle( hThread ) );

        lpFindData = HeapAlloc( GetProcessHeap(),
                        HEAP_ZERO_MEMORY,
                        sizeof(WIN32_FIND_DATA) );

    } while ( FindNextFile( hFindFile, lpFindData ));

    FindClose( hFindFile );
    hFindFile = INVALID_HANDLE_VALUE;

    for (i=0; i<MAX_THREADS; i++)
        WaitForSingleObject( hThreadLimitSemaphore,
                        INFINITE );

    MTVERIFY( CloseHandle( hThreadLimitSemaphore ) );

    return EXIT_SUCCESS;
}
Beispiel #19
0
void CConfigManager::ReadRouteMain(int *pCPUNumberOf)
{
	*pCPUNumberOf = GetPrivateProfileIntA("SYS_INFO", "CPU_NUMBER_OF", -1, "Config\\PostofficeRoute\\PostofficeRoute.ini");

	MTVERIFY( -1!=*pCPUNumberOf );
}
Beispiel #20
0
void CConfigManager::ReadRouteRand(int *pMaxServerPeople)
{
	*pMaxServerPeople = GetPrivateProfileIntA("POSTOFFICE_SERVER", "MAX_SERVER_PEOPLE", 0, "Config\\PostofficeRoute\\PostofficeRoute.ini");

	MTVERIFY( 0!=*pMaxServerPeople );
}
Beispiel #21
0
void EventDlg_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
{
	int rc;

	switch (id)
	{
	case IDC_AUTOMATIC:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										FALSE,		// Automatic (FALSE = not manual)
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		// CreateEvent ALWAYS sets the last error
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("WARNING: Event wasn't destroyed");
		StartThreads();
		AddToList("Event set to AUTOMATIC");
		break;

	case IDC_MANUAL:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										TRUE,		// Manual
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("Reusing old event");
		StartThreads();
		AddToList("Event set to MANUAL");
		break;

	case IDC_SIGNAL:
		MTVERIFY( SetEvent(hEventObject) );
		break;

	case IDC_RESET:
		MTVERIFY( ResetEvent(hEventObject) );
		break;

	case IDC_PULSE:
		MTVERIFY( PulseEvent(hEventObject) );
		break;

	case IDC_CLEAR:
		ListBox_ResetContent(GetDlgItem(hDlg, IDC_RESULTS));
		break;

	case IDCANCEL:
	case IDM_EXIT:
		PostMessage(GetParent(hDlg),WM_DESTROY, (WPARAM)0, (LPARAM)0);
		DestroyWindow(hDlgMain);
		hDlgMain = NULL;
		break;
		
	default:
		break;
	}
}
Beispiel #22
0
//
//±¾Ä£¿é
void CConfigManager::ReadMaxConnectItem()
{
	nMaxConnectItem = GetPrivateProfileIntA("TCP_SOCKET", "MAX_CONNECT_ITEM", -1, "Config\\PostofficeRoute\\PostofficeRoute.ini");
	
	MTVERIFY( -1!=nMaxConnectItem  );
}