Linux多线程编程实例解析
Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的多线程程序 pthread_create.c。
一个重要的线程创建函数原型:
#include
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr, void *(*start_rtn)(void),void *restrict arg);
返回值:若是成功建立线程返回0,否则返回错误的编号
形式参数:
pthread_t *restrict tidp 要创建的线程的线程id指针
const pthread_attr_t *restrict attr 创建线程时的线程属性
void* (start_rtn)(void) 返回值是void类型的指针函数
void *restrict arg start_rtn的行参
例程1:
功能:创建一个简单的线程
程序名称:pthread_create.c
/************************************************* *******************************************
** Name:pthread_create.c
** Used to study the multithread programming in Linux OS
** Author:zeickey
** Date:2006/9/16
** Copyright (c) 2006,All Rights Reserved!
************************************************** *******************************************/
#include
#include
void *myThread1(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 1st pthread,created by zieckey.\n");
sleep(1);//Let this thread to sleep 1 second,and then continue to run
}
}
void *myThread2(void)
{
int i;
for (i=0; i<100; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
sleep(1);
}
}
int main()
{
int i=0, ret=0;
pthread_t id1,id2;
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL); //创建成功返回0,否则非0
if (ret) //表达式值为0,按“假”处理;非0时按“真”处理。
{
printf("Create pthread error!\n");
return 1;
}
ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL); //等待线程1结束
pthread_join(id2, NULL); //等待线程2结束
return 0;
}
我们编译此程序:
# gcc pthread_create.c -lpthread
因为pthread的库不是linux系统