1. 程式人生 > >一步一步學習多執行緒程式設計之CreateThread

一步一步學習多執行緒程式設計之CreateThread

CreatThread函式如下圖所示

在這裡我們只用到了第三個和第四個引數,第三個引數傳遞了一個函式的地址,也是我們要指定的新的執行緒。第四個引數是傳給新執行緒的引數指標。

// ThreadCreateTest.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include<windows.h>

int time = 0;
void ThreadProc1()
{

	int hour = 0;
	int mins = 0;
	while(1)
	{
		hour = time/60;
		mins = time%60;
		
		int day = hour/24;
		
		if (day)
		{
			hour -=day*24;
		}
		time++;
		
		printf("執行緒1 %d:%d\n",hour,mins);
		Sleep(1000);
	   // system("cls");
	}

}

void ThreadProc2()
{
	int hour = 0;
	int mins = 0;
	while(1)
	{
		
		hour = time/60;
	    mins = time%60;
		int day = hour/24;//超過24個小時的話

		if (day)
		{
			hour -=day*24;
		}
		time++;
		printf("執行緒2 %d:%d\n",hour,mins);
		Sleep(1000);
		//system("cls");

	}
}

int main()
{

	HANDLE hThread1  = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc1,NULL,0,0);
	CloseHandle(hThread1);
	HANDLE hThread2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc2,NULL,0,0);
	CloseHandle(hThread2);
	
	getchar();
	return 0;
	
	
}
        儘管上面程式看上去是併發進行,但是有時候也不一定按照執行緒1:執行緒2的輸出。這涉及到多執行緒的同步問題。對於一個資源被多個執行緒共用會導致程式的混亂,我們的解決方法是隻允許一個執行緒擁有對共享資源的獨佔,這樣就能夠解決上面的問題了。

HANDLE CreateMutex

 LPCTSTR);

Parameters

lpMutexAttributes
[in] Ignored. Must be NULL.
bInitialOwner
[in] Boolean that specifies the initial owner of the mutex object. If this value is TRUE and the caller created the mutex, the calling thread obtains ownership of the mutex object. Otherwise, the calling thread does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.
lpName
[in] Long pointer to a null-terminated string specifying the name of the mutex object. The name is limited to MAX_PATH characters and can contain any character except the backslash path-separator character (\). Name comparison is case sensitive.

If lpName matches the name of an existing named mutex object, the bInitialOwner

parameter is ignored because it has already been set by the creation process.

If lpName is NULL, the mutex object is created without a name.

If lpName matches the name of an existing event, semaphore, or file-mapping object, the function fails and theGetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space. 

該函式用於創造一個獨佔資源,第一個引數我們沒有使用,可以設為NULL,第二個引數指定該資源初始是否歸屬建立它的程序,第三個引數指定資源的名稱。



HANDLE hMutex;
void ThreadProc1()
{
	int hour = 0;
	int mins = 0;
	while(1)
	{
		WaitForSingleObject(hMutex, INFINITE);
		hour = time/60;
		mins = time%60;
		
		int day = hour/24;
		
		if (day)
		{
			hour -=day*24;
		}
		time++;
		
		printf("執行緒1 %d:%d\n",hour,mins);
		Sleep(1000);
		ReleaseMutex(hMutex);
	   // system("cls");
	}

}



相關推薦

no