windows C ++ multi-threading (D): _ beginthread use

      windows are normally used to create a thread CreateThread, the CRT function and there is a conflict, try not to use this function, you should use _beginthread, the end of the thread with _endthread, these two sets of functions can be used.

      These two functions need to include header #include <process.h>

     _beginthread the following statement

ACRTIMP uintptr_t __cdecl _beginthread(
    _In_     _beginthread_proc_type _StartAddress,
    _In_     unsigned               _StackSize,
    _In_opt_ void*                  _ArgList
    );

Parameter Description

     _StartAddress thread function address in the following format:

                            typedef void     (__cdecl*   _beginthread_proc_type  )(void*);

                           In fact void ThreadFun (void * param) This form

    _StackSize stack size, with CreateThread, generally filled 0

    _ArgList list of parameters, no parameter is set to NULL

return value

      Successful return to the New thread handle, use reinterpret_cast <HANDLE> cast, if the new thread exits too quickly, you may not return a valid handle.

      Failed to return -1.

 

_endthread terminate the thread

Function declaration as follows:

_ACRTIMP void __cdecl _endthread(void);

This function is recommended, it will automatically clean up resources at the end of the thread created by _beginthread.

Sample Code

#include <process.h>
#include <stdio.h>
#include <windows.h>

void ThreadFun(void* param)
{
	char* p = (char*)param;

	int  n = 0;
	while (++n <= 6)
	{
		Sleep(1000);
		printf("第%d次打印%s\n", n, p);

		//结束_beginthread创建的线程,别用ExitThread退出。
		if (n == 3) 
			_endthread();
	}

	printf("子线程结束!\n");
}

int main()
{
	printf("主线程开始!\n");

	//推荐使用C++运行期库函数_beginthread
	HANDLE  hThread=  (HANDLE)	_beginthread(ThreadFun, 0, "hello");
	WaitForSingleObject(hThread, INFINITE);

	printf("主线程结束!\n");
}

 

Published 134 original articles · won praise 85 · views 160 000 +

Guess you like

Origin blog.csdn.net/yao_hou/article/details/104301154