zoukankan      html  css  js  c++  java
  • MFC学习 多线程

    #include <Windows.h>
    #include <process.h>
    #include <stdio.h>
    
    HANDLE hMutex; //互斥对象
    void ProcessTask(void * args)
    {
        int a = 0;
        WaitForSingleObject(hMutex, INFINITE);
        while ( a < 100)
            printf("_beginthread %d
    ", a++);
        ReleaseMutex(hMutex);
        //结束后会自动调用_endtrhead
    }
    unsigned int _stdcall ProcessTask2(void * args)
    {
        int a = 0;
        WaitForSingleObject(hMutex, INFINITE);
        while ( a < 100)
            printf("_beginthreadex %d
    ", a++);
        ReleaseMutex(hMutex); //如果不释放, 线程结束时, 系统也会释放
        //结束后会自动调用_endtrheadex
        return 0;
    }
    DWORD WINAPI ThreadProc(LPVOID lpParameter)
    {
        int a = 0;
        WaitForSingleObject(hMutex, INFINITE);
        while ( a < 100)
            printf("CreateThread %d
    ", a++);
        ReleaseMutex(hMutex);
        return 0;
    }
    
    int main()
    {
        hMutex = CreateMutex(NULL, FALSE, "tickets");
        if(hMutex)
        {
            if(ERROR_ALREADY_EXISTS == GetLastError())
            {
                printf("one instance has exist
    ");
                system("pause");
                return 0;
            }
        }
        _beginthread(ProcessTask, 0, 0);
        _beginthreadex(NULL, 0, ProcessTask2, NULL, 0, 0);
        Sleep(3000);
        DWORD threadId;
        HANDLE hThread3 = CreateThread(0, 0, ThreadProc, 0, 0, &threadId); //不建议使用, 在处理c库的时间类函数会内在泄漏大约70-80字节
        //创建匿名互斥对象
        //hMutex = CreateMutex(NULL, FALSE, NULL); //第二个参数参数初始化时当前线是否拥有互斥对象, 如果设置发TRUE, 可以用ReleaseMutex释放
        //创建一个命名互斥对象可以判断实例是否在运行
        
        CloseHandle(hThread3);
        system("pause");
        return 0;
    }

    代码下载

  • 相关阅读:
    reflow和repaint
    移动端事件
    不支持冒泡的事件
    Gulp
    JAVAWEB项目Tomcat与内网穿透实现外网访问,可连接mysql数据库
    Echarts连接Mysql使用心得
    layui的date组件在弹窗里闪退的解决办法
    Layui的table标签使用记录
    Layui后台实现页面内部的iframe跳转
    第16周作业
  • 原文地址:https://www.cnblogs.com/barrysgy/p/3225329.html
Copyright © 2011-2022 走看看