zoukankan      html  css  js  c++  java
  • C++多线程一

    CreateThread()创建一个新的线程。

    ExitThread()正常的结束一个线程的执行。

    CloseHandle()关闭一个线程的句柄。

    CreateThread()函数原型如下:

    HANDLE  WINAPI CreateThread(

        LPSECURITY_ATTRIBUTES lpThreadAttributes,//线程安全属性,(NULL表示不能被子进程继承)

        SIZE_T dwStackSize, //线程堆栈初始化大小,默认为0

        LPTHREAD_START_ROUTINE lpStartAddress, //线程函数

        LPVOID lpParameter,  //线程参数

        DWORD dwCreationFlags,//创建方式(0:表示立即执行)

        LPDWORD lpThreadId  //线程标识符(该指针存储线程创建后返回的线程标识符)

    );

    线程函数的格式必须:

    DWORD WINAPI threadName(LPVOID lpParamter);

    // lpParamter为CreateThread()传递给线程函数的参数,函数返回值为函数是否正常结束的标志。

    句柄对线程对象有完全的访问权,句柄可以被子进程继承。线程句柄在其被关闭前一直是有效的,既是句柄所代表的线程已全部被终止,所以必须调用CloseHandle()显式的关闭一个句柄。

    #include <iostream>
    #include <windows.h>
    
    bool repeat=true;
    
    DWORD WINAPI mythread1(LPVOID lpParamter)
    {
        while(repeat)
        {
            std::cout<<"How are you?"<<std::endl;
            Sleep(100);
        }
        DWORD exitCode;
        ExitThread(exitCode);
        return 0;
    }
    
    DWORD WINAPI mythread2(LPVOID lpParamter)
    {
        while(repeat)
        {
            std::cout<<"very well!"<<std::endl;
            Sleep(100);
        }
        DWORD exitCode;
        ::ExitThread(exitCode);
        return 0;
    }
    
    DWORD WINAPI killthread(LPVOID lpParamter)
    {
        repeat=false;
        return 0;
    }
    
    int main()
    {
        HANDLE handle1,handle2,handle3;
        DWORD dw1,dw2,dw3;
        handle1=::CreateThread(NULL,0,mythread1,NULL,0,&dw1);
        if(handle1==NULL)
        {
            std::cout<<"create thread1 failed!"<<std::endl;
            return -1;
        }
    
        handle2=::CreateThread(NULL,0,mythread2,NULL,0,&dw2);
        if(handle2==NULL)
        {
            std::cout<<"create thread2 failed!"<<std::endl;
            return -1;
        }
    
        ::Sleep(500);
        handle3=::CreateThread(NULL,0,killthread,NULL,0,&dw3);
        if(handle3==NULL)
        {
            std::cout<<"create thread3 failed !"<<std::endl;
            return -1;
        }
    
        ::CloseHandle(mythread1);
        ::CloseHandle(mythread2);
        ::CloseHandle(killthread);
    
        return 0;
    }
  • 相关阅读:
    每日日报2020.12.1
    每日日报2020.11.30
    981. Time Based Key-Value Store
    1146. Snapshot Array
    565. Array Nesting
    79. Word Search
    43. Multiply Strings
    Largest value of the expression
    1014. Best Sightseeing Pair
    562. Longest Line of Consecutive One in Matrix
  • 原文地址:https://www.cnblogs.com/hometown/p/3393645.html
Copyright © 2011-2022 走看看