多线程入门(Time to step into multi-threading)

972 篇文章 329 订阅
32 篇文章 6 订阅

      先说明一下CreateThread函数的参数dwCreationFlags, 当它为0的时候,表示线程创建后可以立即进行调度,而不是说线程对应的函数立即执行。

    

     先上一段小代码:

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

DWORD WINAPI ThreadFun(LPVOID pM)
{
	printf("子线程的线程ID号为:%d\n", GetCurrentThreadId());
	return 0;
}

int main()
{
	printf("main thread\n");
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
	CloseHandle(handle);

	return 0;
}

     结果是:main thread ,可见线程对应的函数ThreadFun并没有得到执行,这是因为,主线程的时间片够长,主线程运行完后,进程直接退出了。子线程还没有来得及运行。


     我们将上述程序改为:

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

DWORD WINAPI ThreadFun(LPVOID pM)
{
	printf("子线程的线程ID号为:%d\n", GetCurrentThreadId());
	return 0;
}

int main()
{
	printf("main thread\n");
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
	CloseHandle(handle);

    int i;
	for(i = 0; i < 100; i++)
	{
		; // 延时
	}

	return 0;
}

     结果依然是:main thread ,在这种情况下,主线程的时间片依然没有用完,所以足够主线程运行完成,其它线程没有机会了。

 

     将上述程序改为:

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

DWORD WINAPI ThreadFun(LPVOID pM)
{
	printf("子线程的线程ID号为:%d\n", GetCurrentThreadId());
	return 0;
}

int main()
{
	printf("main thread\n");
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
	CloseHandle(handle);

    int i;
	for(i = 0; i < 1000000; i++)
	{
		; // 延时
	}

	return 0;
}

      运行上面的程序,可以发现,子线程得到了运行,因为主线程需要的时间比较长,而时间片不够,所以其它线程就运行了,等其它线程执行完后,又返回了主线程继续进行执行,直至主线程结束。

 

      我们再来看看WaitForSingleObject函数,该函数的作用是: 等待,使得指定的对象被触发或超时,程序如下:

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

DWORD WINAPI ThreadFun(LPVOID pM)
{
	printf("子线程的线程ID号为:%d\n", GetCurrentThreadId());
	return 0;
}

int main()
{  
	printf("main thread\n");
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
  
	WaitForSingleObject(handle, INFINITE);
	CloseHandle(handle);
	printf("end\n");

	return 0;
}

      结果为(注意,ID号有可能不同):

main thread
子线程的线程ID号为:10032
end

 

      最后,我们来欣赏一下这个程序:

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

DWORD WINAPI ThreadFun(LPVOID pM)
{
	printf("%s\n", pM);
	printf("子线程的线程ID号为:%d\n", GetCurrentThreadId());
	return 0;
}

int main()
{  
	printf("main thread\n");
	HANDLE handle = CreateThread(NULL, 0, ThreadFun, "hello world", 0, NULL);
	CloseHandle(handle);
	while(1)
	{
		;
	}

	printf("end\n");

	return 0;
}


 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值