简单介绍windows平台下的pthread线程库

最近打算尝试写一些跨平台的程序,本想自己封装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来测试:

// main.cpp
#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

嘿嘿!开源就是好啊,跨平台实现得如此容易。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值