linux下多线程(pthread)编程实例,Linux多线程编程实例解析

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系统

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值