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(
LPSECURITY_ATTRIBUTESlpMutexAttributes,
BOOLbInitialOwner,
LPCTSTRlpName );
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.
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"); } }
原文:http://blog.csdn.net/xy010902100449/article/details/44899917