Linux----線程基礎__Linux

來源:互聯網
上載者:User

線程:
線程是執行粒度比進程小的執行流;線程是在進程的地址空間內啟動並執行一個控制序列。
在Linux中線程有獨立的PCB,為了實現在核心中進行切換有獨立的上下文,調用函數時開闢棧幀有私人棧,線程有自己的調度優先順序,自己的訊號屏蔽字;各個線程共用一個進程地址空間,共用檔案描述符表,遇到的異常訊號處理方式相同,共用進程中的某些資源,各自完成進程分配的任務。

線程是如何進行標識的
每個線程都有屬於自己的id,擷取線程id有兩種方式:
1. pthread_t pthread_self()

2. #include<sys/syscall.h>
pid_t tid;
tid=syscall(SYS_gettid);

線程是如何進行建立的

int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void* (start_routine)(void*),void* arg)
參數:thread:標識線程的id;
attr:設定線程的屬性,NULL表示預設屬性;
start_routine:函數地址,線程啟動時調用的函數;
arg:傳給線程啟動函數的參數。
傳回值:成功返回0,失敗返回錯誤碼。

註:連結函數庫時在Makefile裡一定要使用編譯器命令選項-lpthread.

#include<stdio.h>#include<stdlib.h>void* thread_run(void* arg){      while(1)      {          printf("get a thread:%s\n",(char*)arg);          sleep(1);    }}int main() {    pthread_t tid;    pthread_create(&tid,NULL,thread_run,"thread-1"); while(1)   {        printf("I am main thread!\n");        sleep(2);    }  return 0;}

線程如何終止
線程終止有三種方式:
1.void pthread_exit(void* value_ptr)
註:主線程的退出表示進程的退出,不能調用此函數,父進程獲得進程的退出碼,所以需要以進程的方式進行退出。

2.int pthread_cancel(pthread_t thread)
注意:線程不能在自己的執行函數中取消自己。
成功返回0,失敗返回錯誤碼。

3.線程函數中return返回

線程的等待和分離

//線程等待int pthread_join(pthread_thread,void** value_ptr)參數:thread:線程id;value_ptr:指向一個指標,這個指標指向線程的傳回值。傳回值:成功返回0,失敗返回錯誤碼

線程退出時,空間沒有被釋放,需要執行此函數對空間進行清理;
保證建立的線程不會複用剛才線程退出的地址空間。

//線程分離1.線程組內其他進程對目標進程進行分離int pthread_detach(pthread_t thread)2.線程自己分離int pthread_detach(pthread_t pthread_self())
  #include<stdio.h>  #include<stdlib.h>  void* thread_run(void* arg)  {     printf("I am %s\n",(char*)arg);     sleep(1);     return (void*)1;  }  int main()  {     pthread_t tid;     void* tmp;     pthread_create(&tid,NULL,thread_run,"thread");     pthread_detach(tid);//線程分離     pthread_join(tid,&tmp);//線程等待     printf("main thread is run,thread return!tmp:%d\n",(int)tmp);     return 0;  }


線程分離之後,當線程退出的時候不需要再進行線程等待進行空間的釋放清理,這些工作自動化完成。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.