【Linux基础】线程基本操作

在这里我们介始是Pthread线程库,它是由POSIX提供的一套通用的线程库,具有很好的移植性。Pthread线程库是一套用户级线程库,在linux上实现时,是使用了内核级线程来完成,目的是为了提高线程的并发性。
线程创建和退出
1.函数说明
在linux中,创建线程所用的函数是pthread_create.而创建线程实际上就是确定调用该线程函数的入口点。线程退出有两种方法:一种是在线程被创建后,就开始运行相关的线程函数,在该函数运行完之后,该线程也就退出了;另一种是使用函数pthread_exit主动退出。在这里应注意到,线程退出使用函数pthread_exit,而进程退出是使用函数exit,当使用函数exit让进程终止时,进程中所有线程都会终止。上一章说到在进程之间用函数wait来同步终止和释放资源,而线程之间实现这样的机制是用函数pthread_join。函数pthread_join可用于将当前线程挂起,等待线程的结束。这个函数是一个线程阻塞函数,调用它的函数将一直到被等待的线程结束为止,当函数返回时,被等待线程的资源被回收。
2.函数格式
(1)pthread_create 函数语法要点

01.jpg (74.92 KB, 下载次数: 0)

下载附件保存到相册设为封面

2013-6-6 15:00 上传

02.jpg (60.76 KB, 下载次数: 0)

下载附件保存到相册设为封面

2013-6-6 15:00 上传

3.函数实例
分别创建两个线程,当线程结束时调用pthread_exit函数退出,其一个线程在运行的过程中进行sleep。在主线程中收集这两个线程的退出信息,并释放资源。
/*thread.c*/
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void thread1(void)
{
int i=0;
while(i<3)
{
printf("i= %d in pthread1\n",i);
i++;
sleep(5);
}
pthread_exit(0);
}
void thread2(void)
{
int i=0;
while(i<5)
{
printf("i= %d in pthread2\n",i);
i++;
}
pthread_exit(0);
}
int main(void)
{
pthread_t thrd1,thrd2;
int ret;
ret=pthread_create(&thrd1,NULL,(void *)thread1,NULL);
if(ret=0)
{
printf("create thread1 fail\n");
exit(1);
}
ret=pthread_create(&thrd2,NULL,(void *)thread2,NULL);
if(ret=0)
{
printf("create thread2 fail\n");
exit(1);
}
pthread_join(thrd1,NULL);
pthread_join(thrd2,NULL);
exit(0);
}
运行结果为:
[root@localhost thread]# ./thread
i= 0 in pthread1
i= 0 in pthread2
i= 1 in pthread2
i= 2 in pthread2
i= 3 in pthread2
i= 4 in pthread2
i= 1 in pthread1
i= 2 in pthread1
 
本文转载于唯C教育,【Linux基础】线程基本操作
http://www.weicedu.com/forum.php?mod=viewthread&tid=119&fromuid=4
(出处: http://www.weicedu.com/)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值