虚位以待(AD)
虚位以待(AD)
首页 > 操作系统 > LINUX > Linux线程

Linux线程
类别:LINUX   作者:码皇   来源:互联网   点击:

1 定义,线程是在进程内部运行的一个执行分支,即线程是在进程的地址空间运行,执行进程的一个分支。2 Linux下的线程,Linux下没有真正意义的线程,是使用进程模拟的,在Linux下,线程叫做轻量级进程,使用task_struct结构体描述,而Windows下存在线程TCB。

1.定义

线程是在进程内部运行的一个执行分支,即线程是在进程的地址空间运行,执行进程的一个分支。

2.Linux下的线程

Linux下没有真正意义的线程,是使用进程模拟的,在Linux下,线程叫做轻量级进程,使用task_struct结构体描述,而Windows下存在线程TCB。

3.线程与进程的区别

①进程强调资源独占,线程强调资源共享;

②进程是承担系统资源分配的一个实体,线程是在进程内部运行的执行流;

③进程是提供资源的基本单位,它有一个或多个执行流,线程是调度的基本单位;

④线程对进程的大部分资源共享,但也有私有资源,每个线程各一份:

共享资源:文件描述符、各种信号的处理方式、当前工作目录、用户ID和组ID;

私有资源:线程ID、上下文、栈空间、errno变量、信号屏蔽字、调度优先级;

4.线程控制

(1)线程创建:pthread_create( )

(2)线程等待:pthread_join( )

(3)线程终止:
方法①:在线程中return,在主线程中return ,表示当前进程退出;
方法②:自己调用pthread_exit((void*)321)终止;
方法③:调用pthread_cancel( ) 取消线程;

5.实现进程创建、等待、终止:
编译时要链接需要的库 -lpthread

    #include#include#includevoid *thread_fun1(void* arg)//线程return被终止{
    printf("thread1 returning...n");
    return (void*)1;
    }
    void *thread_fun2(void* arg)//线程自己调用exit函数退出{
    printf("thread2 exiting...n");
    pthread_exit((void*)2);
    }
    void *thread_fun3(void* arg)//线程被其他线程调用pthread_cancel取消{
    while(1) {
    printf("thread3 is waitting for cancel...n");
    sleep(1);
    }
    return (void*)1;
    }
    int main(){
    pthread_t tid;
    void* ret;
    //方法一: pthread_create(&tid,NULL,thread_fun1,NULL);
    pthread_join(tid,&ret);
    printf("thread1 return,tid1:%d,return code is:%dn",tid,(int)ret);
    //方法二: pthread_create(&tid,NULL,thread_fun2,NULL);
    pthread_join(tid,&ret);
    printf("thread2 exit,tid1:%d,return code is:%dn",tid,(int)ret);
    //方法三: pthread_create(&tid,NULL,thread_fun3,NULL);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid,&ret);
    printf("thread3 return,tid1:%d,return code is:%dn",tid,(int)ret);
    return 0;
    }

结果如图:

6.线程的分离与结合

①在任何时间,线程是可分离,也可结合的;

②一个可结合的线程能够被其他线程收回资其源和杀死,在回收前,它的存储器资源不被释放 ,一个分离的线程不能被其他线程回收和杀死的,它的存储器资源在它终止时被系统自动释放;

③默认情况下,线程被创建为可结合的,每个可结合线程都要被显示地回收,调用pthread_join;

④调用pthread_join后,线程没有运行结束,调用者会被堵塞,所以在子线程或父线程中调用pthread_detach,将子进程状态设置为分离的,那么该线程运行结束后会自动释放所有资源。

    #include #include #include void* pthread_fun(void* arg){
    pthread_detach(pthread_self());
    printf("child detach!n");
    return NULL;
    }
    int main(){
    pthread_t tid;
    int tret = pthread_create(&tid, NULL, pthread_fun, NULL);
    if(tret != 0) {
    perror("pthread_create");
    return -1;
    }
    int ret = 0;
    sleep(1);
    if(0 == pthread_join(tid, NULL)) {
    printf("pthread wait success!n");
    ret = 0;
    }
    else {
    printf("pthread wait failed!n");
    ret = 1;
    }
    return ret;
    }

结果如图:

相关热词搜索:
上一篇:LinuxLVM硬盘扩容
下一篇:Linux基础操作