用Windows API实现多线程--原理例子

来源:互联网 发布:现代网络小说家排行榜 编辑:程序博客网 时间:2024/05/10 13:08

首先必须包含头文件windows.h
下面是一个简单的例子:在主函数中开启新的子线程执行函数f()。

#include <windows.h>
#include <iostream>
using namespace std;


void WINAPI f1(LPVOID pvThread)
{
    while (true)
    {
        printf("inside thread 1/n");
        Sleep(1000);
    }
}


void WINAPI f2(LPVOID pvThread)
{
    while (true)
    {
        printf("inside thread 2/n");
        Sleep(2000);
    }
}


int main()
{
    HANDLE hThread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)f1,NULL,0,NULL);
    HANDLE hThread2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)f2,NULL,0,NULL);
   
    if(hThread1 != NULL)
    {
        WaitForSingleObject(hThread1, INFINITE);
        CloseHandle(hThread1);
    }
    if(hThread2 != NULL)
    {
        WaitForSingleObject(hThread2, INFINITE);
        CloseHandle(hThread2);
    }
    return 0;
}

其中
if(hThread != NULL)
{
   WaitForSingleObject(hThread, INFINITE);
   CloseHandle(hThread);
}
这一段很重要,这段让主线程保持住。如果没有这段的话,执行完上一句,主线程不等子线程执行就退出,从而子线程也跟着退出了,就达不到效果。

参考整理于此处:http://topic.csdn.net/t/20020811/00/931486.html#

原创粉丝点击