对Linux多线程的理解

Linux多线程

一、线程的特点

1. 线程是进程的一个执行流,是CPU调度和分配的基本单位。线程是程序运行的最小单位。

2. 线程不会影响到其它线程的运行。比如一个线程崩溃,其它线程正常运行。

3. 同一进程内的线程共享进程的地址空间。

二、一个线程的组成

1. 一个指向当前被执行指令的指令指针

2. 一个栈空间

3. 一个寄存器值的集合

4. 一个私有的数据区

三、使用线程的优点

1. 同一进程下的多线程共享地址空间,减少的资源的浪费。

2. 线程间方便的通信机制。因为线程共享数据空间,所以通信十分方便。

3. 操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。

4. 改善程序结构。可以任务拆分成多个小任务,方便管理。

四、POSIX线程接口函数

1. 创建线程 -- pthread_create

函数原型:int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg);

函数参数:thread  --线程标识符。

                  attr  --线程的属性,一般为NULL。

                  start_routine  --线程的执行函数,没有为NULL。

                  arg  --传入到线程执行函数的参数。

头文件:#include <pthread.h>

返回值:成功返回0,出错为非0。

2. 线程的退出 -- pthread_exit

函数原型:void pthread_exit(void *value_ptr);

函数参数:value_ptr  --线程结束的返回值。

头文件:#include <pthread.h>

注意:线程的退出只能由自己调用。

3. 等待线程 -- pthread_join

函数原型:int pthread_join(pthread_t thread, void **value_ptr);

函数参数:thread  --线程的标识符。

               value_ptr  --不为NULL,储存线程结束的返回值。

头文件:#include <pthread.h>

返回值:成功返回0,出错返回非0。

五、参考代码

#include <stdio.h>
#include <pthread.h>

void *myThread1(void)
{
    int i;
    for (i=0; i<3; 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<3; i++)
    {
        printf("This is the 2st pthread,created by zieckey.\n");
        sleep(1);
    }
}

int main()
{
    int i=0, ret=0;
    pthread_t id1,id2;

    /*创建线程1*/
    ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
    if (ret)
    {
        printf("Create pthread error!\n");
        return 1;
    }

    /*创建线程2*/
    ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
    if (ret)
    {
        printf("Create pthread error!\n");
        return 1;
    }

    pthread_join(id1, NULL);
    pthread_join(id2, NULL);

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值