2024年5月25日发(作者:)
Linux下C多线程编程实例
Linux下C多线程编程
2007-08-24 10:07:56
Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写
Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库
libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用
clone()来实现的。clone()是Linux所特有的系统调用,它的使用方
式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关
文档说明。下面我们展示一个最简单的多线程程序example1.c。
/* example.c*/
#include
#include
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.n");
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.n");
pthread_join(id,NULL);
return (0);
}
我们编译此程序:
gcc example1.c -lpthread -o example1
运行example1,我们得到如下结果:
This is the main process.
This is a pthread.
This is the main process.
This is the main process.
This is a pthread.
This is a pthread.
再次运行,我们可能得到如下结果:
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
前后两次结果不一样,这是两个线程争夺CPU资源的结果。上面的示
例中,我们使用到了两个函数,pthread_create和pthread_join,并声
明了一个pthread_t型的变量。
pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:
typedef unsigned long int pthread_t;
它是一个线程的标识符。函数pthread_create用来创建一个线程,
它的原型为:
extern int pthread_create __P ((pthread_t *__thread, __const
pthread_attr_t *__attr,void *(*__start_routine) (void *), void
*__arg));
第一个参数为指向线程标识符的指针,第二个参数用来设置线程属
性,第三个参数是线程运行函数的起始地址,最后一个参数是运行函数的
参数。这里,我们的函数thread不需要参数,所以最后一个参数设为空
指针。第二个参数我们也设为空指针,这样将生成默认属性的线程。对线
程属性的设定和修改我们将在下一节阐述。当创建线程成功时,函数返回
0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和
EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表
示第二个参数代表的线程属性值非法。创建线程成功后,新创建的线程则
运行参数三和参数四确定的函数,原来的线程则继续运行下一行代码。
函数pthread_join用来等待一个线程的结束。函数原型为:
extern int pthread_join __P ((pthread_t __th, void


发布评论