C语言 多线程使用说明2

没看1的小伙伴进我空间先看看1吧。//1代表的是上一篇csdn水文

运行1中的程序,会发现标准输出设备中只有main thread is running,而没有fun thread is runing,为啥呢?

对于主线程而言,操作系统为他分配了时间片因此能够运行。在main中,先用《2》创建线程,然后关闭线程句柄,之后在执行标号四的代码,然后该函数推出,也就是说主线程执行完成了,然后进程也就退出了,namely,新创建的线程还没有得到执行的机会就推出了,因此窗口中没有看到Fun thread is running。

为了让它得到运行的机会就需要主线程暂停运行,即放弃执行的权力,操作系统从等待运行的线程队列中选取一个运行。

在程序中,如果需要某个线程暂停运行,可以调用Sleep函数,使得语句所在的线程段暂停多少毫秒。

在1中,我们在return前面添加一个Sleep(10)让主线程暂停10ms,操作系统就会选择剩下那个线程来执行,当线程1执行完毕后,或者是10ms间隔时间已过,主线程就会恢复运行,main函数退出,进程结束,这下控制台的窗口就既能看到:

Damn,main thread is running和Yes,sir,fun thread is running了。

比如我们写这么一段:

#include "stdafx.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<math.h>
#include <Windows.h>
DWORD WINAPI Fun(LPVOID lpParameter);
int index = 0;
int main(void)
{
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
	CloseHandle(hThread1);
	while (index++ < 20)
		printf("main thread is running\n");
	system("pause");
	return 0;
}
DWORD WINAPI Fun(LPVOID lpParameter)
{
	while (index++ < 20)
		printf("fun thread is running\n");
	return 0;
}

就能看到有并发运行的一段。

猜你喜欢

转载自blog.csdn.net/qq_42229034/article/details/81813125