首頁  >  文章  >  後端開發  >  在C程式中的Windows執行緒API

在C程式中的Windows執行緒API

PHPz
PHPz轉載
2023-09-05 19:17:10524瀏覽

在C程式中的Windows執行緒API

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

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

例如,如果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</p><p>");
      return -1;
   }
   Param = atoi(argv[1]);
   if (Param < 0){
      fprintf(stderr,"An integer >= 0 is required</p><p>");
      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</p><p>",Sum);
   }
}
#

以上是在C程式中的Windows執行緒API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除