pthread_create用法
来源:互联网 发布:lofter个性域名怎么弄 编辑:程序博客网 时间:2024/05/22 06:47
#include <pthread.h>int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void *restrict arg);
Returns: 0 if OK, error number on failure
C99 中新增加了 restrict 修饰的指针: 由 restrict 修饰的指针是最初唯一对指针所指向的对象进行存取的方法,仅当第二个指针基于第一个时,才能对对象进行存取。对对象的存取都限定于基于由 restrict 修饰的指针表达式中。 由 restrict 修饰的指针主要用于函数形参,或指向由 malloc() 分配的内存空间。restrict 数据类型不改变程序的语义。 编译器能通过作出 restrict 修饰的指针是存取对象的唯一方法的假设,更好地优化某些类型的例程。
第一个参数为指向线程标识符的指针。第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
下面这个程序中,我们的函数
thr_fn
不需要参数,所以最后一个参数设为空指针。第二个参数我们也设为空指针,这样将生成默认属性的线程。当创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,原来的线程则继续运行下一行代码。#include<stdio.h>
#include<pthread.h>#include<string.h>
#include<sys/types.h>
#include<unistd.h>
pthread_t ntid;
void printids(constchar *s){
pid_t pid;
pthread_t tid;
pid= getpid();
tid= pthread_self();
printf("%s pid %u tid %u (0x%x)\n",s,(unsignedint)pid,(unsignedint)tid,(unsigned
int)tid);
}
void *thr_fn(void*arg){
printids("new thread:");
return((void*)0);
}
int main(){
int err;
err= pthread_create(&ntid,NULL,thr_fn,NULL);
if(err!= 0)
{
printf("can't create thread: %s\n",strerror(err));
return 1;
}
printids("main thread:");
sleep(1);
return 0;
}
把APUE2上的一个程序修改一下,然后编译。
结果报错:
pthread.c:(.text+0x85):对‘pthread_create’未定义的引用
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:gcc -o pthread -lpthread pthread.c
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create()用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create用法
- pthread_create的用法
- linux c++ pthread_create 用法
- pthread_create 函数用法
- C/C++基本数据类型所占字节数
- 爱加密:解析APP开发团队生存难题
- poj 2115||zoj2305(扩展欧几里德)
- 《程序员》 -- 并轨国际,中国开源基金会即将扬帆起航——记中国开源基金会微峰会
- 仿百度搜索的文本框(第二种实现ajax联想查询的文本框)
- pthread_create用法
- 编码分类
- 基于Visual C++2013拆解世界五百强面试题--题11-查找数字出现次数
- java自学笔记之面向对象多态
- JTextField利用setDocument方式来设置文本框输入的内容
- ubuntu下hadoop源代码安装
- 日志切换 redo log 频繁
- 【网络基础】TCP协议的三次握手过程
- JAVA解析JSON相关