线程

来源:互联网 发布:查重率软件 编辑:程序博客网 时间:2024/06/07 23:05

       今天我们来分享一下,Linux下的线程的简单概念和相关实现及验证。

       首先必须明确的一点是Linux下没有真正的线程,Linux下的线程是由进程来模拟的,因此Linux下的线程也被称为轻量级进程。

    进程(PCB):承担分配资源的基本实体。

    线程(TCB):调度的基本单位。而且线程是在进程内部运行的执行分支(执行流),线程其本质是在进程的地址空间上运行。

    也因为Linux中没有真正的线程,所以Linux没有相应的系统调用接口来管理线程,所以我们引入pthread库来进行线程相应管理和一系列操作。

线程创建--thread_creat

       Linux中没有线程,用户借助pthread库来主动创建线程。

线程等待--thread_join

       主线程需要等待其他线程来避免,主线程先于其他线程退出,导致其他线程运行结果和资源无人管理和回收,从而导致的类僵尸进程状态而造成的内存泄漏问题。

       线程创建和等待代码截图和运行结果如下:

 

 

 

终止线程的三种方式

   1.return :终止当前进程

   2.thread_exit:终止当前进程

   3.thread_cancal:取消当前进程

      终止线程的代码截图和运行结果如下:

 

 

线程取消--thread_cancal

       可以在其他线程中取消其他线程(被取消),同样也可以在自己的线程中取消自己(取消),代码截图和验证性的运行结果如下:

 自己取消:

 

 

 被取消:

 

 

线程分离--thread_death

    线程分离后,主线程可不必等待该线程。即该线程“独立”出去了,主线程可以不用管理该线程的运行结果和资源,但是如果该线程运行出现重大错误,被系统等kill时,所有与该线程相关的线程(包括主线程和其他子线程)都会被一起kill。

       同样的,线程分离可以自己分离也可以被分离。

       当线程自己分离,且主线程仍旧(强行)等待时,主线程可能会表示线程等待成功。代码截图和验证性的运行结果如下:

 

 

      当线程被分离,且主线程仍旧(强行)等待时,主线程会报错。代码截图和验证性的运行结果如下:

 

 

查看进程和线程的命令行命令

       用ps _aux|grep mythread查看进程和用ps _aL|grep mythread查看线程的方法,截图结果如下:

 


原代码如下示:

mythread.c

#include<stdio.h>   #include<pthread.h>      void* thread_fun(void* arg){       int val = (int)arg;   //  pthread_detach(pthread_self());       int i=0;       while(i<5){           printf("this is new pthread, pid:%d, tid:%u, val:%d\n",getpid(), pthread    _self(), val);          i++;          if(i>2)pthread_cancel(pthread_self());//3      }      //return (void*)124;//1      //pthread_exit((void*)23);//2  }    int main(){      pthread_t tid;        if(pthread_create(&tid, NULL, thread_fun, NULL)<0){          perror("pthread_creat");          return -1;      }        printf("this is main pthread, pid:%d, tid:%u\n",getpid(), pthread_self()); //  pthread_detach(tid);    //  pthread_cancel(tid);     //int i=0;     //while(i<5){     //  printf("this is main pthread, pid:%d, tid:%u\n",getpid(), pthread_self()    );      //  i++;      //  sleep(1);  //  }        void* code;      int ret = pthread_join(tid, &code);      if(ret == 0){          printf("wait successed!code:%d\n", (int)code);      }      else{       printf("error code:%d, error string:%s\n", code, strerror(ret));      }      return 0;  }

Makefile 

mythread:mythread.c      gcc -o $@ $^ -lpthread  .PHONY:clean  clean:      rm -f mythread

  分享到此结束!望大家天天有进步!


 

原创粉丝点击