vs2012创建线程

创建线程

创建线程方法一、

HANDLE WINAPI CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, // 线程安全属性
SIZE_T dwStackSize, // 线程堆栈大小
LPTHREAD_START_ROUTINE lpStartAddress, // 线程函数地址
LPVOID lpParameter, // 线程函数参数
DWORD dwCreationFlags, // 指定线程是否立即启动
LPDWORD lpThreadId // 存储线程ID号
);
线程内核对象就是一个包含了线程状态信息的数据结构。每次对CreateThread 的成功调用,系统都会在内部为其分配一个内核对象。
线程上下文反应了线程上次执行的寄存器状态,来保证线程之间切换(即还原现场)。
计数器,调用一次OpenThread(CreateThread ),计数器加1,CloseThread(CloseHandle)计数器减一。当计数器值为0时,没有线程使用该内核对象,系统收回内存。计数器的初始值是2(主线程是1,创建的线程是2)。

创建线程方法二、C++底部的,并不是Windows标准API,创建线程函数,该函底层调用CreateThread。

#include <process.h>
uintptr_t _beginthreadex(
void *security, // 线程安全属性
unsigned stack_size, // 线程堆栈大小
unsigned ( *start_address )( void * ), //线程函数地址
void *arglist, //传递给线程函数的参数
unsigned initflag, // 指定线程是否立即启动
unsigned *thrdaddr // 存储线程ID号
);
安全属性

typedef struct _SECURITY_ATTRIBUTES {

DWORD nLength;  
LPVOID lpSecurityDescriptor;  
BOOL bInheritHandle;                //设置该句柄可以继承

} SECURITY_ATTRIBUTES,
*PSECURITY_ATTRIBUTES,
*LPSECURITY_ATTRIBUTES;
线程终止

线程函数退出。

    线程使用的堆栈被释放。
    dwExitCode设置为线程函数的返回值。
    递减内核中的code值,让内核的引用计数减一。

// 结束线程调用,终止自己
VOID WINAPI ExitThread(
__in DWORD dwExitCode // 线程结束时的退出码
);
// 由当前线程终止其他线程
BOOL WINAPI TerminateThread(
__in_out HANDLE hThread, // 终止的线程句柄
__in DWORD dwExitCode // 退出码
);
// 进程退出
VOID WINAPI ExitProcess(
__in UINT uExitCode // 退出码
);
void _endthreadex(
unsigned retval // 退出码
);

例程1:

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

DWORD WINAPI ThreadProFunc(LPVOID lpParam);

int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;

hThread = CreateThread( NULL	// 默认安全属性
					, NULL		// 默认堆栈大小
					, ThreadProFunc // 线程入口地址
					, NULL	//传递给线程函数的参数
					, 0		// 指定线程立即运行
					, &dwThreadId	//线程ID号
					);

for(int i = 0; i < 4; i++) {
	printf("nihao\n");
}

CloseHandle(hThread);	//关闭线程句柄,内核引用计数减一

system("pause");
return 0;

}

DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
for(int i = 0; i < 4; i++) {
printf(“hello\n”);
}
return 0;
}

运行结果:

nihao
hello
hello
nihao
hello
nihao
nihao
hello
请按任意键继续. . .

例程2:

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

unsigned int WINAPI ThreadProFunc(void *pParam);

int main(int argc, char **argv)
{
HANDLE hThread;
unsigned int threadId;

hThread = (HANDLE)_beginthreadex(NULL, NULL, ThreadProFunc,NULL, 0, &threadId); 

for(int i = 0; i < 4; i++) {
	printf("nihao\n");
}

CloseHandle(hThread);	//关闭线程句柄

system("pause");
return 0;

}

unsigned int WINAPI ThreadProFunc(void *pParam)
{
for(int i = 0; i < 4; i++) {
printf(“hello\n”);
}
return 0;
}

运行结果

nihao
hello
hello
nihao
hello
nihao
nihao
hello

猜你喜欢

转载自blog.csdn.net/weixin_41454036/article/details/108442589