linux – 多处理器机器中posix线程的并发性

我对多处理器机器中posix线程的并发性有一些疑问.我在SO中发现了类似的问题,但没有找到确凿的答案.

以下是我的理解.我想知道我是否正确.

> Posix线程是用户级线程,内核不知道它.
>内核调度程序会将Process(及其所有线程)视为一个调度实体.它是线程库,它反过来选择运行哪个线程.它可以在可运行的线程中分割内核给出的CPU时间.
>用户线程可以在不同的cpu核心上运行.即让线程T1& T2由进程(T)创建,然后T1可以在Cpu1中运行,T2可以在Cpu2中运行但是它们不能同时运行.

如果我的理解正确,请告诉我.

谢谢…

最佳答案
由于您使用“Linux”标记标记了您的问题,我将根据linux下的标准pthreads实现来回答它.如果您正在谈论“green” threads,它们是在VM /语言级而不是操作系统上安排的,那么您的答案大多是正确的.但我在下面的评论是关于Linux pthreads.

1) Posix threads are user level threads and kernel is not aware of it.

不,这当然不正确. Linux内核和pthreads库一起管理线程.内核执行上下文切换,调度,内存管理,缓存内存管理等.当然,在用户级别还有其他管理,但没有内核,pthreads的大部分功能都会丢失.

2) Kernel scheduler will treat Process( with all its threads) as one entity for scheduling. It is the thread library that in turn chooses which thread to run. It can slice the cpu time given by the kernel among the run-able threads.

不,内核将每个进程线程视为一个实体.它有自己的关于时间切片的规则,它将进程(和进程优先级)考虑在内,但每个子进程线程都是一个可调度的实体.

3) User threads can run on different cpu cores. ie Let threads T1 & T2 be created by a Process(T),then T1 can run in Cpu1 and T2 can run in Cpu2 BUT they cant run concurrently.

不可以.多线程程序需要并发执行.这就是为什么同步和互斥体如此重要以及程序员为什么忍受多线程编程的复杂性的原因.

向您证明这一点的一种方法是使用-L选项查看ps的输出以显示关联的线程. ps通常将多个线程进程包装成一行但是使用-L可以看到内核为每个线程都有一个单独的虚拟进程ID:

ps -ef | grep 20587
foo    20587     1  1 Apr09 ?        00:16:39 java -server -Xmx1536m ...

ps -eLf | grep 20587
foo    20587     1 20587  0  641 Apr09 ?    00:00:00 java -server -Xmx1536m ...
foo    20587     1 20588  0  641 Apr09 ?    00:00:30 java -server -Xmx1536m ...
foo    20587     1 20589  0  641 Apr09 ?    00:00:03 java -server -Xmx1536m ...
...

我不确定Linux线程是否仍然这样做,但历史上pthreads使用clone(2)系统调用来创建自己的另一个线程副本:

Unlike fork(2),these calls allow the child process to share parts of its execution context with the calling process,such as the memory space,the table of file descriptors,and the table of signal handlers.

这与fork(2)不同,fork(2)在创建另一个完整进程时使用.

相关文章

linux常用进程通信方式包括管道(pipe)、有名管道(FIFO)、...
Linux性能观测工具按类别可分为系统级别和进程级别,系统级别...
本文详细介绍了curl命令基础和高级用法,包括跳过https的证书...
本文包含作者工作中常用到的一些命令,用于诊断网络、磁盘占满...
linux的平均负载表示运行态和就绪态及不可中断状态(正在io)的...
CPU上下文频繁切换会导致系统性能下降,切换分为进程切换、线...