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/