Linux下类似windows下_beginthread和_endthread 的多线程开发
来源:互联网 发布:c语言标准库函数源码 编辑:程序博客网 时间:2024/05/20 03:05
在 windows下头文件中包含 #include<process.h>
就可以使用_beginthread进行线程创建。个人感觉挺方便的。
在linux下类似于_beginthread 和 _endthread 的 是pthread_create和pthread_exit
linux下包含头文件 #include<pthread.h>
=================================
pthread_create 启动线程属性讲解:
http://blog.csdn.net/hudashi/article/details/7709413
===================================
下面是转载的一个例子:
原文地址:http://yecheng110.blog.hexun.com/13030352_d.html
#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(const char *s){pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)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
- Linux下类似windows下_beginthread和_endthread 的多线程开发
- 线程的终止_beginthread和_endthread或者CloseHandle()
- Windows下创建线程的方法_beginThread和CreateThread区别
- 多线程下 ,linux和 windows开发应注意的区别
- 多线程下 ,linux和 windows开发应注意的区别
- _beginthread,_endthread未定义错误
- _beginthread, _endthread, CreateThread, ExitThread
- linux下的多线程开发
- windows和linux下多线程的一些区别
- Windows下C语言多线程函数_beginthread简单入门应用例子
- Windows 内核下的多线程开发
- RabbitVCS : Linux下类似windows TortoiseSVN的svn客户端
- 【Linux开发】Linux下的多线程编程
- 【Linux开发】Linux下的多线程编程
- 【Linux开发】Linux下的多线程编程
- windows下类似linux编译环境搭建
- windows下类似linux readdir()读取文件
- Windows和linux下的Java串口开发( javacomm20/RXTX)
- Ubuntu根目录下各文件的功能介绍
- Android下调整多媒体音量方法
- 游戏中按概率播放某个音效简单c++实现
- string转int 等(转)
- MFC-Dialog各函数的执行顺序
- Linux下类似windows下_beginthread和_endthread 的多线程开发
- SAP系统参数设置
- linux c++下载http文件并显示进度<转>
- 言必信,行必果,硁硁然小人哉!
- c++实现一个比较两个string类型的版本号的小demo
- Android 解压zip文件(支持中文)
- Eclipse 工程使用相对路径导入Jar包设置
- android中配置文件property的用途以及使用<转>
- PocketSphinx语音识别系统的编程