zoukankan      html  css  js  c++  java
  • 线程的互斥量问题

    线程互斥是为了解决线程的冲突问题。
    同一个互斥量,只能解决64个线程,这是家用电脑的限制,在服务器上就不会。

    #include <stdio.h>
    #include <Windows.h>
    
    HANDLE mutex = NULL;//指针
    int  num = 0;
    
    DWORD WINAPI add(void *p)
    {
        WaitForSingleObject(mutex, INFINITE);
        for (int i = 0; i < 100000;i++)
        {
            num++;
        }
        ReleaseMutex(mutex);    //释放这个对象
    
    }
    
    
    
    int main()
    {
        mutex = CreateMutex(NULL, FALSE, NULL);//创建一个互斥量
        //FALSE表示不激活,TRUE表示激活
        if (mutex==NULL)
        {
            //互斥量创建失败
        }
        HANDLE hd[64];//线程互斥,同一个互斥量,只能解决64个
        for (int i = 0; i < 64;i++)
        {
            hd[i] = CreateThread(NULL, 0, add, NULL, 0, NULL);
            if (hd[i]==NULL)
            {
                //创建失败
            }
        }
    
        WaitForMultipleObjects(64, hd, TRUE, INFINITE);
    
    
        printf("%d", num);
    
        for (int i = 0; i < 64;i++)//关闭每一个线程的资源
        {
            CloseHandle(hd[i]); 
        }
    
        CloseHandle(mutex);//关闭排斥
    
        system("pause");
  • 相关阅读:
    《Spring2之站立会议1》
    《Spring1之第十次站立会议》
    《Spring1之第九次站立会议》
    《Spring1之第八次站立会议》
    《Spring1之第七次站立会议》
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/sjxbg/p/5769496.html
Copyright © 2011-2022 走看看