Posix Threads API (pthreads) 是在並行編程中用到的非常普通的API,這套API包括許多非常基礎的同步方法,方便我們編寫高效的多線程程式。然而,Microsoft Windows 並不包含這樣的介面。幸運的是,這裡有一個開源的Windows平台上的 Pthread 實現。
- Pthreads Implementation on Microsoft Windows
- 開源協議:BSD License
- 官方網址:http://locklessinc.com/articles/pthreads_on_windows/
- :http://locklessinc.com/downloads/
下載下來僅僅是一個 winpthreads.h 檔案,把這個檔案包含在project中即可使用。
下面是使用這個API的一個例子,在Visual Studio 2008/2010/2012中編譯通過,在Windows 7/Windows 8上運行無誤:
#include <stdio.h>#include <tchar.h>#include <winpthreads.h>/* This is our thread function. It is like main(), but for a thread */void *threadFunc(void *arg){char *str;int i = 0;str = (char*)arg;while(i < 10 ){Sleep(1);printf("threadFunc says: %s\n",str);++i;}return NULL;}int _tmain(int argc, _TCHAR* argv[]){pthread_t pth;// this is our thread identifierint i = 0;/* Create worker thread */pthread_create(&pth,NULL,threadFunc,"processing...");/* wait for our thread to finish before continuing */pthread_join(pth, NULL /* void ** return value could go here */);while(i < 10 ){Sleep(1);printf("main() is running...\n");++i;}return 0;}
運行結果:
參考文獻:
- Pthreads on Microsoft Windows http://locklessinc.com/articles/pthreads_on_windows/
- POSIX Threads http://en.wikipedia.org/wiki/POSIX_Threads
- Multithreading in C, POSIX style http://softpixel.com/~cwright/programming/threads/threads.c.php
- pthreads-win32 http://sourceware.org/pthreads-win32/