C++多线程的创建与使用

来源:互联网 发布:短信恢复软件免费版 编辑:程序博客网 时间:2024/06/06 02:12
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

DWORD WINAPI run(LPVOID p)
{
    printf("three%d run../n",p);
    Sleep((DWORD)p*3000);
    return (DWORD)p;
}

int main()
{
    HANDLE three1    = NULL;    //线程
    HANDLE three2    = NULL;
    DWORD uExitCode1 = 0;   // 返回值
    DWORD uExitCode2 = 0;
    DWORD dwThId     = 0;
    DWORD dwThId1    = 0;    // 线程id号
    int c            = 0;

    three1 = CreateThread (NULL, 0, run, (LPVOID)1, 0, &dwThId);
    three2 = CreateThread (NULL, 0, run, (LPVOID)2, 0, &dwThId1);    
        
    for (;;)
    {   
        puts ("press any key to check thread ...");

        _getch ();
        //'GetExitCodeThread'函数来判断一个线程是否还在执行 说明 获取一个已     
        // 中止线程的退出代码 返回值 bool,非零表示成功,零表示失败。...
   
        GetExitCodeThread (three2, &uExitCode2);
   
        if (!c)
        {
            GetExitCodeThread (three1, &uExitCode1);
            
            if (uExitCode1 == STILL_ACTIVE)
            {
                puts ("Thread1 still active");
            }
            else
            {
                printf ("Thread1 over with: %d/n", dwThId);

                CloseHandle (three1);
                c = 1;

                printf ("Thread1 over with: %d/n",dwThId);
            }
        }
        
        if (uExitCode2 == STILL_ACTIVE)
        {
            puts("Thread2 still active");
        }
        else
        {
            printf ("Thread2 over with: %d/n",dwThId1);
        }
   
        if ((uExitCode1!=STILL_ACTIVE) && (uExitCode2!=STILL_ACTIVE))
        {
            break;
        }
    }
    // CloseHandle(three1); // 关闭线程句柄并不影响线程的执行
    CloseHandle(three2);

    return EXIT_SUCCESS;
}
原创粉丝点击