線程使用共享堆而非私有堆的原因分析

進程創建線程,每個線程可以共享進程的地址空間;但同時線程需要保留一些自己私有的數據

unix中的thread獨自持有的資源:

  • Stack pointer
  • Registers
  • scheduling properties(policy and priority)
  • set of pending and blocked signals
  • Thread specific data
線程操作的特點:
  • Changes made by one thread to shared system resources will be seen by all other threads
  • Two pointers(may belong by different threads) have the same value point to the same data
  • Reading and Writing to the same memory locations need explicit synchronization by programmer
使用線程的優勢:
  • Light weight: can be created with less overhead(process: fork(); thread: pthread_creat())
  • Efficient communication / Data exchange(not copy data opration, just need to pass address)
一個進程創建的多個線程:每個線程都擁有自己私有的Stack,但共享一個Heap
這樣做的原因

(1)stack is for local/method variables;  heap is for instance/class variable

(2)Stack常常用來存放 函數的參數,函數中使用的自動變量,存放過程活動記錄;如果多個線程共享一個Stack
會非常的凌亂,不方便使用

(3)使用共享Heap的目的是爲了高效的數據共享


線程間的數據交換有兩種方式:

(1)共享內存方式shared memory(共享堆):最大的優勢是快速
(2)消息傳遞方式message passing(不需要共享堆):優勢在於安全






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章