C程式中的Windows執行緒API


執行緒是在Windows API中使用CreateThread()函式建立的,並且——就像在Pthreads中一樣——一組屬性(如安全資訊、堆疊大小和執行緒標誌)被傳遞給此函式。在下面的程式中,我們使用這些屬性的預設值。(預設值最初不會將執行緒設定為掛起狀態,而是使其有資格由CPU排程程式執行。)建立求和執行緒後,父執行緒必須等待它完成才能輸出Sum的值,因為該值是由求和執行緒設定的。在Pthread程式中,我們讓父執行緒使用pthread join()語句等待求和執行緒。在這裡,使用WaitForSingleObject()函式,我們在Windows API中執行等效的操作,這會導致建立執行緒阻塞,直到求和執行緒退出。在需要等待多個執行緒完成的情況下,使用WaitForMultipleObjects()函式。此函式傳遞四個引數:

  • 要等待的物件數量
  • 指向物件陣列的指標
  • 一個標誌,指示是否所有物件都已發出訊號。
  • 超時持續時間(或INFINITE)

例如,如果THandles是大小為N的執行緒HANDLE物件陣列,則父執行緒可以使用此語句等待其所有子執行緒完成:

WaitForMultipleObjects(N, THandles, TRUE, INFINITE);

使用Windows API的多執行緒C程式。

示例

#include<windows.h>
#include<stdio.h>
DWORD Sum;
/* data is shared by the thread(s) */
/* thread runs in this separate function */
DWORD WINAPI Summation(LPVOID Param){
   DWORD Upper = *(DWORD*)Param;
   for (DWORD i = 0; i <= Upper; i++)
   Sum += i;
   return 0;
}
int main(int argc, char *argv[]){
   DWORD ThreadId;
   HANDLE ThreadHandle;
   int Param;
   if (argc != 2){
      fprintf(stderr,"An integer parameter is required
");       return -1;    }    Param = atoi(argv[1]);    if (Param < 0){       fprintf(stderr,"An integer >= 0 is required
");       return -1;    }    /* create the thread */    ThreadHandle = CreateThread( NULL, /* default security attributes */ 0, /* default stack size */        Summation, /* thread function */ &Param, /* parameter to thread function */ 0, /* default creation    flags */ &ThreadId);    /* returns the thread identifier */    if (ThreadHandle != NULL){       /* now wait for the thread to finish */ WaitForSingleObject(ThreadHandle,INFINITE);       /* close the thread handle */       CloseHandle(ThreadHandle);       printf("sum = %d
",Sum);    } }

更新時間: 2019年10月16日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告