多线程基础知识

参加了一次multithreading的team内部training,做了些note:

1. 多核CPU,必然配备对应个数的register组。并且,如果是超线程CPU,比如6核超线程CPU,可以有6*2组register。

2. 一个线程,有它自己单独的stack以及TLS。对于一般的单线程程序,因为就一个main主线程,感觉就一个stack,实际只是因为只有一个线程在跑。

3. Fiber VS thread (或许需要进一步的总结):

  1)如果有Fiber这一级的管理调度,那么它是线程内的。Fiber从属于某一个线程。 

    2)thread是OS级进行支持的,线程的调度由OS执行,并且现代的OS多是抢占式多任务处理;Fiber是没有OS级支持的,完全由用户来调度控制,因此可以是抢占式或协同式多任务处理模式。

4. CPU of course is moving forward to provide more and more powerful atomic instruction set..

5. 做了多线程化工作后,肯定是需要measure它的效果的(how much performance has been improved by using multi-threading?)。有两个公式从理论上提供了方法,不过实践性上并不那么好。这两个公式说明了两个问题:

    --for legacy app, only portion of it can be parallelled: %=(s+p) / (s+p/n)

    --any sufficiently large problem can be efficiently parallelized. 比如原来花2分钟可以打开一个2M的模型,而多线程化后花2分钟可以打开一个20M的模型(哦?好像不是很能说明问题)。

6. 线程安全(thread safety)的概念:当多个线程同时访问一个函数时,对于任何一个线程这个函数都能保证以它所承诺的contract来“以同样的输入参数给出同样的执行结果”。当然,在一个函数中使用static/global data, system level resouces很容易导致线程不安全。。

7. Dead(b)lock相关概念:

    -- dead(b)lock. How to prove your design won't bring in deadlock?? 4 conditions... if one of the 4 is not met, then you win!

    -- livelock

8. Race, about resources threads all want.
    -- Signal... CriticalSection, Mutex.

9. XXFree --- different levels of parallel quality..

10. 对于一个多线程应用程序,一个线程的exit只代表那个线程的结束而已。但是如果是主线程exit呢?是否意味着整个应用程序的exit即进程的结束呢? NO.

static void Main()  (from MSDN)  
{
// Create the threads that will use the protected resource.
for(int i = 0; i < numThreads; i++)
{
Thread myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
myThread.Start();
}
// The main thread exits, but the application continues to

// run until all foreground threads have exited.

}
原文地址:https://www.cnblogs.com/taoxu0903/p/1938545.html