进程创建线程,每个线程可以共享进程的地址空间;但同时线程需要保留一些自己私有的数据
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)
(1)stack is for local/method variables; heap is for instance/class variable
(2)Stack常常用来存放 函数的参数,函数中使用的自动变量,存放过程活动记录;如果多个线程共享一个Stack 会非常的凌乱,不方便使用
(3)使用共享Heap的目的是为了高效的数据共享
线程间的数据交换有两种方式:
(1)共享内存方式shared memory(共享堆):最大的优势是快速 (2)消息传递方式message passing(不需要共享堆):优势在于安全