Linux首先需要安装GCC/G++编译环境,方法本文从略,然后建个test.c或test.cpp文件。
本文测试系统Ubuntu 11.10。GCC编译器截至发文日期止最新的版本,现在不在办公室下次补上。
1、pthread_create函数定义
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void), void *restrict arg);
参数1:指向线程标识符指针。
参数2:线程属性。
参数3:线程运行函数起始地址。
参数4:运行函数的参数。
创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。
2、源码包含pthread头文件
include <pthread.h>
3、创建多线程示例程序C格式
#include <stdio.h>
#include <stdlib.h>
pthread_t ntid;
void *fnThreadFun(void *para){
//...
return ((void *)0);
}
int main(){
int err;
err = pthread_create(&ntid,NULL,fnThreadFun,NULL);
if(err != 0){
printf("can't create thread: %d\n",strerror(err));
return 1;
}
sleep(1);
return 0;
}
4、创建多线程示例程序C++格式(代码部分我是在原作者基础上修改的,我的系统Ubuntu10.04)
ctest.h
#include<stdio.h>
#include<stdlib.h>
class ctest{
public:
ctest();
~ctest();
void createthread();
};
ctest.cpp
#include "ctest.h"
ctest::ctest(){
printf("cpp_thread constructor\n");
}
ctest::~ctest(){
printf("cpp_thread destructor\n");
}
void *fnThreadFunc(void *para){
int i=0;
while(i<3){
printf("num is %d \t",i++);
}
return (void*)0;
}
void ctest::createthread(){
pthread_t n_tid;
int err = pthread_create(&n_tid, NULL, fnThreadFunc,NULL);
if(err!= 0){
printf("can't create thread: %d\n", err);
}
pthread_join(n_tid,NULL);
}
test.cpp
#include"ctest.h"
int main(){
ctest tst;
tst.createthread();
return 0;
}
另外,也可以把线程函数设计到类中,但是必须声明为static类型,天缘认为完全没这个必要,因为static类型函数在编译时仍然是先分配全局地址,反倒直接用全局似乎看起来更规整,就是注意点,把函数名取好就可以了。
4、编译执行多线程程序
编译上述多线程程序,必须使用 -lpthread编译选项,因为pthread库不是Linux默认链接库,链接时必须指定使用libpthread.a库(天缘机子ubuntu11.10这些库在/usr/lib/i386-linux-gnu路径下),在编译选项中需添加-lpthread参数,示例如:
C编译选项:
>gcc test.c -o test -lpthread
C++编译选项:
>g++ ctest.cpp test.cpp -o test -lpthread
如果是写到MAKEFILE中,可以找到类似TARG_OPTIONS=这样的位置添加-lpthread。
但是往往还是会报告pthread_create未声明问题,说明编译器仍未找到libpthead.a的位置,这时可手动在编译命令行中添加:-L./usr/lib/i386-linux-gnu 选项(这里的路径是libthread.a路径,不同系统、机子可能有所不同!!)。
执行:
>./test
5、pthread注意事项
注意,pthread_create第三个参数,也就是线程回调函数格式为:
void* fnThreadFun(void* param)
{
return NULL;//或return ((void *)0);
}
其返回值为void*型指针,如果写成void fnThreadFun(void* param)形式,那么编译会报告:
error: invalid conversion from ‘void (*)(void*)’ to ‘void* (*)(void*)’ [-fpermissive]
错误。
写成:
err = pthread_create(&ntid,NULL,(void*)&fnThreadFun,NULL);
样式似乎也不行,gcc编译时不会出错,但是用g++就会有问题(也会报告上面错误。),究其原因就是C语言编译器允许隐含性的将一个通用指针转换为任意类型的指针,而C++不允许(http://www.4ucode.com/Study/Topic/1353180)。
参考地址:
http://zhuwenlong.blog.51cto.com/209020/40339
线程互斥和解锁请参考:
http://www.ibm.com/developerworks/cn/linux/l-cn-mthreadps/index.html
http://hi.baidu.com/see_yee/blog/item/139fe0243198ad34c8955917.html
http://en.wikipedia.org/wiki/POSIX_Threads
天缘原创博客,转载或使用必须遵守署名、非商业用途和保持一致,未经许可严禁对本文去链接、去水印、去署名或伪原创等演绎行为,转载请注明:
转载自 天缘博客 及本文链接地址:http://www.metsky.com/archives/550.html