最近打算尝试写一些跨平台的程序,本想自己封装windows下的CreateThread和linux下的pthread,后来查查资料,发现Linux社区早就提供了
windows下的pthread库,和linux下一模一样,爽。
windows下的pthread库叫做:pthreads-win32,官方网站是:http://sourceware.org/pthreads-win32/,官方FTP是:
ftp://sources.redhat.com/pub/pthreads-win32/。
郁闷的是,FTP里面的内容比较乱,部分已经编译的库有问题。我下载了一个看起来比较新的库,结果弄了半天不能链接。建议大家下载:
ftp://sources.redhat.com/pub/pthreads-win32/pthreads-w32-2-7-0-release.exe这个自解压文件,压缩包里的pthreads.2目录是源码,
Pre-built.2目录是编译所需的头文件和库文件。
先把pthreads-w32-2-7-0-release.exe解压缩到c:\pthreads-w32-2-7-0-release文件夹。
OK!现在写一个简单的pthread来测试:
#include < stdio.h >
#include < pthread.h >
#include < assert.h >
void * Function_t( void * Param)
... {
printf("我是线程! ");
pthread_t myid = pthread_self();
printf("线程ID=%d ", myid);
return NULL;
}
int main()
... {
pthread_t pid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&pid, &attr, Function_t, NULL);
printf("======================================== ");
getchar();
pthread_attr_destroy(&attr);
return 1;
}
OK!使用微软的CL来编译:
rem cl.bat
cl.exe main.cpp /c /I"c:\pthreads-w32-2-7-0-release\Pre-built.2\include"
link.exe /out:main_cl.exe main.obj /LIBPATH:"c:\pthreads-w32-2-7-0-release\Pre-built.2\lib" pthreadVC2.lib
pause
或者使用GCC来编译:
rem gcc.bat
g++.exe -o main.o -c main.cpp -I"c:\pthreads-w32-2-7-0-release\Pre-built.2\include"
g++.exe -o main_gcc.exe main.o "c:\pthreads-w32-2-7-0-release\Pre-built.2\lib\libpthreadGC2.a"
pause
嘿嘿!开源就是好啊,跨平台实现得如此容易。