Win32 Thread API学习

第一个 API :创建一个线程

CreateThread()

The CreateThread function creates a thread to execute within the address space of the calling process.

HANDLE CreateThread(

    LPSECURITY_ATTRIBUTES lpThreadAttributes,                // pointer to thread security attributes 

    DWORD dwStackSize,                // initial thread stack size, in bytes

    LPTHREAD_START_ROUTINE lpStartAddress,  // pointer to thread function

    LPVOID lpParameter,// argument for new thread

    DWORD dwCreationFlags,        // creation flags

    LPDWORD lpThreadId                // pointer to returned thread identifier

   );

Return Values

If the function succeeds, the return value is a handle to the new thread.

If the function fails, the return value is NULL. To get extended error information, call etLastError.

Example1: 创建一个线程

#include <windows.h>

 

DWORD WINAPI threadFunc (LPVOIDpArg)

{

       return 0;

}

 

main ()

{     

       HANDLE hThread;

       hThread = CreateThread (NULL, 0, threadFunc, NULL, 0, NULL );

       return 0;

}

 

上面这段代码有一个小问题,那就是 threadFunc 有可能不会被执行到就结束了!要保证 threadFunc 肯定被执行(也就是等线程退出),在 CreateThread 后加一行代码:

                WaitForMultipleObjects (1, &hThread, TRUE, INFINITE);



第二个
API :等待线程返回

WaitForMultipleObjects

The WaitForMultipleObjects function returns when one of the following occurs:

Either any one or all of the specified objects are in the signaled state.

The time-out interval elapses.

DWORD WaitForMultipleObjects(

    DWORD nCount,          // number of handles in the object handle array

    CONST HANDLE *lpHandles,   // pointer to the object-handle array

    BOOL bWaitAll,             // wait flag

    DWORD dwMilliseconds           // time-out interval in milliseconds

   );

If dwMilliseconds is INFINITE, the function's time-out interval never elapses.

Example2: 四个线程一起运行

#include <Windows.h>

#include <stdio.h>

const int numThreads = 4;

 

DWORD WINAPI threadFunc(LPVOIDpArg)

{

       int *p = (int *)pArg;

       int num = *p;

       printf("threadFunc...%d.../n", num);

       return 0;

}

 

int main()

{

       HANDLE hThread[numThreads];

       int threadNum[numThreads];

       for(inti=0; i<numThreads; i++)

       {

              threadNum[i] = i;

              hThread[i] = CreateThread(NULL, 0, threadFunc, &threadNum[i], 0, NULL);

       }

      

       WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);

       return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值