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

进程创建线程,每个线程可以共享进程的地址空间;但同时线程需要保留一些自己私有的数据

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(不需要共享堆):优势在于安全






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