使用多线程实际上是很是容易的,下面这个程序的主线程会建立了一个子线程并等待其运行完毕,子线程就输出它的线程ID号而后输出一句经典名言——Hello World。整个程序的代码很是简短,只有区区几行。程序员
//最简单的建立多线程实例 #include <stdio.h> #include <windows.h> //子线程函数 DWORD WINAPI ThreadFun(LPVOID pM) { printf("子线程的线程ID号为:%d\n子线程输出Hello World\n", GetCurrentThreadId()); return 0; } //主函数,所谓主函数其实就是主线程执行的函数。 int main() { printf(" 最简单的建立多线程实例\n"); printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n"); HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL); WaitForSingleObject(handle, INFINITE); return 0; }
下面来细讲下代码中的一些函数面试
第一个 CreateThread编程
函数功能:建立线程windows
函数原型:安全
HANDLEWINAPICreateThread( LPSECURITY_ATTRIBUTESlpThreadAttributes, SIZE_TdwStackSize, LPTHREAD_START_ROUTINElpStartAddress, LPVOIDlpParameter, DWORDdwCreationFlags, LPDWORDlpThreadId );
函数说明:多线程
第一个参数表示线程内核对象的安全属性,通常传入NULL表示使用默认设置。dom
第二个参数表示线程栈空间大小。传入0表示使用默认大小(1MB)。函数
第三个参数表示新线程所执行的线程函数地址,多个线程可使用同一个函数地址。ui
第四个参数是传给线程函数的参数。this
第五个参数指定额外的标志来控制线程的建立,为0表示线程建立以后当即就能够进行调度,若是为CREATE_SUSPENDED则表示线程建立后暂停运行,这样它就没法调度,直到调用ResumeThread()。
第六个参数将返回线程的ID号,传入NULL表示不须要返回该线程ID号。
函数返回值:
成功返回新线程的句柄,失败返回NULL。
第二个 WaitForSingleObject
函数功能:等待函数 – 使线程进入等待状态,直到指定的内核对象被触发。
函数原形:
DWORDWINAPIWaitForSingleObject( HANDLEhHandle, DWORDdwMilliseconds );
函数说明:
第一个参数为要等待的内核对象。
第二个参数为最长等待的时间,以毫秒为单位,如传入5000就表示5秒,传入0就当即返回,传入INFINITE表示无限等待。
由于线程的句柄在线程运行时是未触发的,线程结束运行,句柄处于触发状态。因此能够用WaitForSingleObject()来等待一个线程结束运行。
函数返回值:
在指定的时间内对象被触发,函数返回WAIT_OBJECT_0。超过最长等待时间对象仍未被触发返回WAIT_TIMEOUT。传入参数有错误将返回WAIT_FAILED
CreateThread()函数是Windows提供的API接口,在C/C++语言另有一个建立线程的函数_beginthreadex(),在不少书上(包括《Windows核心编程》)提到过尽可能使用_beginthreadex()来代替使用CreateThread(),这是为何了?下面就来探索与发现它们的区别吧。
首先要从标准C运行库与多线程的矛盾提及,标准C运行库在1970年被实现了,因为当时没任何一个操做系统提供对多线程的支持。所以编写标准C运行库的程序员根本没考虑多线程程序使用标准C运行库的状况。好比标准C运行库的全局变量errno。不少运行库中的函数在出错时会将错误代号赋值给这个全局变量,这样能够方便调试。但若是有这样的一个代码片断:
if (system("notepad.exe readme.txt") == -1) { switch(errno) { ...//错误处理代码 } }
假设某个线程A在执行上面的代码,该线程在调用system()以后且还没有调用switch()语句时另一个线程B启动了,这个线程B也调用了标准C运行库的函数,不幸的是这个函数执行出错了并将错误代号写入全局变量errno中。这样线程A一旦开始执行switch()语句时,它将访问一个被B线程改动了的errno。这种状况必需要加以免!由于不仅仅是这一个变量会出问题,其它像strerror()、strtok()、tmpnam()、gmtime()、asctime()等函数也会遇到这种由多个线程访问修改致使的数据覆盖问题。
为了解决这个问题,Windows操做系统提供了这样的一种解决方案——每一个线程都将拥有本身专用的一块内存区域来供标准C运行库中全部有须要的函数使用。并且这块内存区域的建立就是由C/C++运行库函数_beginthreadex()来负责的。下面列出_beginthreadex()函数的源代码(我在这份代码中增长了一些注释)以便读者更好的理解_beginthreadex()函数与CreateThread()函数的区别。
//_beginthreadex源码整理By MoreWindows( http://blog.csdn.net/MoreWindows ) _MCRTIMP uintptr_t __cdecl _beginthreadex( void *security, unsigned stacksize, unsigned (__CLR_OR_STD_CALL * initialcode) (void *), void * argument, unsigned createflag, unsigned *thrdaddr ) { _ptiddata ptd; //pointer to per-thread data 见注1 uintptr_t thdl; //thread handle 线程句柄 unsigned long err = 0L; //Return from GetLastError() unsigned dummyid; //dummy returned thread ID 线程ID号 // validation section 检查initialcode是否为NULL _VALIDATE_RETURN(initialcode != NULL, EINVAL, 0); //Initialize FlsGetValue function pointer __set_flsgetvalue(); //Allocate and initialize a per-thread data structure for the to-be-created thread. //至关于new一个_tiddata结构,并赋给_ptiddata指针。 if ( (ptd = (_ptiddata)_calloc_crt(1, sizeof(struct _tiddata))) == NULL ) goto error_return; // Initialize the per-thread data //初始化线程的_tiddata块即CRT数据区域 见注2 _initptd(ptd, _getptd()->ptlocinfo); //设置_tiddata结构中的其它数据,这样这块_tiddata块就与线程联系在一块儿了。 ptd->_initaddr = (void *) initialcode; //线程函数地址 ptd->_initarg = argument; //传入的线程参数 ptd->_thandle = (uintptr_t)(-1); #if defined (_M_CEE) || defined (MRTDLL) if(!_getdomain(&(ptd->__initDomain))) //见注3 { goto error_return; } #endif // defined (_M_CEE) || defined (MRTDLL) // Make sure non-NULL thrdaddr is passed to CreateThread if ( thrdaddr == NULL )//判断是否须要返回线程ID号 thrdaddr = &dummyid; // Create the new thread using the parameters supplied by the caller. //_beginthreadex()最终仍是会调用CreateThread()来向系统申请建立线程 if ( (thdl = (uintptr_t)CreateThread( (LPSECURITY_ATTRIBUTES)security, stacksize, _threadstartex, (LPVOID)ptd, createflag, (LPDWORD)thrdaddr)) == (uintptr_t)0 ) { err = GetLastError(); goto error_return; } //Good return return(thdl); //线程建立成功,返回新线程的句柄. //Error return error_return: //Either ptd is NULL, or it points to the no-longer-necessary block //calloc-ed for the _tiddata struct which should now be freed up. //回收由_calloc_crt()申请的_tiddata块 _free_crt(ptd); // Map the error, if necessary. // Note: this routine returns 0 for failure, just like the Win32 // API CreateThread, but _beginthread() returns -1 for failure. //校订错误代号(能够调用GetLastError()获得错误代号) if ( err != 0L ) _dosmaperr(err); return( (uintptr_t)0 ); //返回值为NULL的效句柄 }
讲解下部分代码:
注1._ptiddataptd;中的_ptiddata是个结构体指针。在mtdll.h文件被定义:
typedefstruct_tiddata * _ptiddata
微软对它的注释为Structure for each thread's data。这是一个很是大的结构体,有不少成员。本文因为篇幅所限就不列出来了。
注2._initptd(ptd, _getptd()->ptlocinfo);微软对这一句代码中的getptd()的说明为:
/* return address of per-thread CRT data */
_ptiddata __cdecl_getptd(void);
对_initptd()说明以下:
/* initialize a per-thread CRT data block */
void__cdecl_initptd(_Inout_ _ptiddata _Ptd,_In_opt_ pthreadlocinfo _Locale);
注释中的CRT (C Runtime Library)即标准C运行库。
注3.if(!_getdomain(&(ptd->__initDomain)))中的_getdomain()函数代码能够在thread.c文件中找到,其主要功能是初始化COM环境。
由上面的源代码可知,_beginthreadex()函数在建立新线程时会分配并初始化一个_tiddata块。这个_tiddata块天然是用来存放一些须要线程独享的数据。事实上新线程运行时会首先将_tiddata块与本身进一步关联起来。而后新线程调用标准C运行库函数如strtok()时就会先取得_tiddata块的地址再将须要保护的数据存入_tiddata块中。这样每一个线程就只会访问和修改本身的数据而不会去篡改其它线程的数据了。所以,若是在代码中有使用标准C运行库中的函数时,尽可能使用_beginthreadex()来代替CreateThread()。相信阅读到这里时,你会对这句简短的话有个很是深入的印象,若是有面试官问起,你也能够流畅准确的回答了^_^。
接下来,相似于上面的程序用CreateThread()建立输出“Hello World”的子线程,下面使用_beginthreadex()来建立多个子线程:
//建立多子个线程实例 #include <stdio.h> #include <process.h> #include <windows.h> //子线程函数 unsigned int __stdcall ThreadFun(PVOID pM) { printf("线程ID号为%4d的子线程说:Hello World\n", GetCurrentThreadId()); return 0; } //主函数,所谓主函数其实就是主线程执行的函数。 int main() { printf(" 建立多个子线程实例 \n"); printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n"); const int THREAD_NUM = 5; HANDLE handle[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; i++) handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, NULL, 0, NULL); WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE); return 0; }
图中每一个子线程说的都是同一句话,不太好看。能不能来一个线程报数功能,即第一个子线程输出1,第二个子线程输出2,第三个子线程输出3,……。要实现这个功能彷佛很是简单——每一个子线程对一个全局变量进行递增并输出就能够了。代码以下:
//子线程报数 #include <stdio.h> #include <process.h> #include <windows.h> int g_nCount; //子线程函数 unsigned int __stdcall ThreadFun(PVOID pM) { g_nCount++; printf("线程ID号为%4d的子线程报数%d\n", GetCurrentThreadId(), g_nCount); return 0; } //主函数,所谓主函数其实就是主线程执行的函数。 int main() { printf(" 子线程报数 \n"); printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n"); const int THREAD_NUM = 10; HANDLE handle[THREAD_NUM]; g_nCount = 0; for (int i = 0; i < THREAD_NUM; i++) handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, NULL, 0, NULL); WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE); return 0; }