多线程(1)

概念
1.线程是进程的一个执行流,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。
2.一个进程由几个线程组成(拥有很多相对独立的执行流的用户程序共享应用程序的大部分数据结构),线程与同属一个进程的其他的线程共享进程所拥有的全部资源。
3.进程——资源分配的最小单位,线程——程序执行的最小单位
4.进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。
好处
1.和进程相比,线程是一种非常“节俭”的多任务操作方式.运行于一个进程中的多个线程,它们之间使用相同的地址空间,而且线程间彼此切换所需的时间也远远小于进程间切换所需要的时间.据统计,一个进程的开销大约是一个线程开销的30倍左右
2. 线程间方便的通信机制。
对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过进程间通信的方式进行,这种方式不仅费时,而且很不方便。
线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便

API
头文件:#include <pthread.h>
1.phtread_create()
函数的作用:创建一个线程
原型:int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routime)(void*),void *arg)
参数:thread:线程的标识符
attr:线程的属性,一般设为NULL;
start_routine:线程的执行函数
arg:传入到线程的执行函数
返回值:成功为0,失败<0;
2.pthread_exit()
函数的作用:线程的退出
原型:void pthread_exit(void *retval)
返回值:成功为0,失败<0;
3.pthread_join()
函数的作用:等待线程的退出
原型:int pthread_join(pthread_t *th,void **thread_return)
参数:th:线程的标识符
thread_return:不为NULL时存储线程结束时的返回值
返回值:成功为0,失败<0;

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

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);
    if (ret)
    {
        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, 0);
    pthread_join(id2, NULL);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值