18.C語言多線程總結

來源:互聯網
上載者:User

標籤:read   總結   window   orm   amp   leave   initial   定義   define   

  • 建立一個線程
    1 _beginthread(myfun, 0, NULL);//傳回值是一個HANDLE
    1 hd[i] = CreateThread(NULL, 0, add, NULL, 0, NULL);//建立線程

     

  • 線程內部結束
    1 _endthread()

     

  • 外部暫停線程
    1 SuspendThread(hd[0]);

     

  • 外部恢複線程
    1 ResumeThread(hd[0]);

     

  • 外部結束一個線程
    1 ExitThread(th[0]);

     

  • 建立臨界區
    1 CRITICAL_SECTION cs1;

    臨界區支援的最大線程數為64

  • 初始化臨界區
    1 InitializeCriticalSection(&cs1);

     

  • 進入臨界區
    1 EnterCriticalSection(&cs1);

     

  • 離開臨界區
    1 LeaveCriticalSection(&cs1);

     

一個樣本,一百個線程每個線程對一個變數進行操作

 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 #define N 64//臨界區最大線程64 5  6 CRITICAL_SECTION cs1 ;//定義臨界區 7  8  9 int num = 0;//多線程訪問會造成衝突,要用到臨界區10 11 DWORD WINAPI myfun(void *p)12 {13     //進入臨界區14     EnterCriticalSection(&cs1);15     for (int i = 0; i < 10000; i++)16     {17         num++;    18     }19     //離開臨界區20     LeaveCriticalSection(&cs1);21     return 0;22 }23 24 void main()25 {26     //初始化臨界區27     InitializeCriticalSection(&cs1);28     //線程數組29     HANDLE hd[N];30     for (int i = 0; i < N; i++)31     {32         //數組每一個元素都是一個線程33         //hd[i] = (HANDLE)_beginthread(myfun, 0, NULL);34         hd[i]=CreateThread(NULL, 0, myfun, NULL, 0, NULL);35         //WaitForSingleObject(hd[i], INFINITE);//等一個線程退出再執行36     }37     //等待所有的線程退出38     WaitForMultipleObjects(N, hd, TRUE, INFINITE);39 40     printf("%d\n", num);41 42     //刪除臨界區43     DeleteCriticalSection(&cs1);44     system("pause");45 }

 

18.C語言多線程總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.