您的位置:首页 > 运维架构 > Linux

Linux环境下多线程系列之线程控制

2017-03-24 22:02 225 查看
【线程的概念】

线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程。

线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。一个线程可以创建和撤消另一个线程,同一进程中的多个线程之间可以并发执行。

【线程和进程的关系】

通常在一个进程中可以包含若干个线程,它们可以利用进程所拥有的资源。在引入线程的操作系统中,通常都是把进程作为分配资源的基本单位,而把线程作为独立运行和独立调度的基本单位。由于线程比进程更小,基本上不拥有系统资源,故对它的调度所付出的开销就会小得多,能更高效的提高系统内多个程序间并发执行的程度,从而显著提高系统资源的利用率和吞吐量。

本篇文章主要介绍了几种简易的线程控制方法:

线程的创建与终止:

创建:


返回值:成功返回0,失败返回错误号。

终止:如果thread线程通过return返回,value_ptr所指向的单元⾥里存放的是thread线程函数的返

回值。

2. 如果thread线程被别的线程调⽤用pthread_cancel异常终掉,value_ptr所指向的单元⾥里存放

的是常数PTHREAD_CANCELED。

3. 如果thread线程是⾃自⼰己调⽤用pthread_exit终⽌止的,value_ptr所指向的单元存放的是传给

pthread_exit的参数。 如果对thread线程的终⽌止状态不感兴趣,可以传NULL给value_ptr

参数。

源代码:
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>

void *thread_1run(void *arg)
{
printf("the new1 pid is %d,tid is %d\n",getpid(),pthread_self());
return((void *)1);
}
void *thread_2run(void *arg)
{
printf("the new2 pid is %d,tid is %d\n",getpid(),pthread_self());
pthread_exit((void *)2);
return NULL;
}
void *thread_3run(void *arg)
{
int i=3;
while(1)
{
printf("the new3 pid is %d,tid is %d\n",getpid(),pthread_self());
sleep(1);
}
return NULL;
}

int main()
{
pthread_t id;
void *temp;
pthread_create(&id,NULL,thread_1run,NULL);
pthread_join(id,&temp);
printf("thread1 return ,thread id is:%u,return code is:%d\n",id,(int)temp);
pthread_create(&id,NULL,thread_2run,NULL);
pthread_join(id,&temp);
printf("thread2 exit ,thread id is:%u,return code is:%d\n",id,(int)temp);
pthread_create(&id,NULL,thread_3run,NULL);

sleep(2);
pthread_cancel(id);
pthread_join(id,&temp);
printf("thread3 cancle ,thread id is:%u,return code is:%d\n",id,(int)temp);
printf("the main pid is %d,tid is %d\n",getpid(),pthread_self());
//	printf("return code is %d",(int)val);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: