| thread 是最近較為流行的一種趨勢,thread 可分為兩種:user-level 和 kernel-level,這兩種方法各有其優缺點,以下是他們的比較:
The advantages of kernel-level threads over user-level threads are:
- supports multiprocessors;
- possibly smoother scheduling, since the same scheduler (the kernel's)
handles both threads and other Unix processes;
- no special action needed to make blocking system call suspend only
the calling thread, not all threads of the process (user-level
threads usually rely on a combination of select() and jacketing of
C library functions for system calls);
- as a consequence of the above, more efficient I/O and
timer-based operations (no need for extra select() and gettimeofday()).
The disadvantages are:
- more expensive context switches between threads, at least when blocking
on conditions and mutexes;
- thread creation is more expensive.
--- 引自 LinuxThreads -- 由上面的比較可以清楚的發現 kernel-level 是一個比較好的選擇, 也算是發展的趨勢吧,下面舉個在 Solaris 下的 thread 範例:
#define _REENTRANT
#include <thread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 10
#define SLEEP_TIME 10
void *sleeping(char *);
int i;
thread_t tid[NUM_THREADS];
void main(int argc,char *argv[])
{
for (i=0;i<NUM_THREADS;i++)
thr_create(NULL,0,sleeping,"4",0,&tid[i]);
while (thr_join(NULL,NULL,NULL) == 0)
;
printf("main() reporting that all %d threads have terminated\n",i);
}
void *sleeping(char *sleep_time )
{
printf(" thread %d sleeping %d seconds\n",thr_self(),atoi(sleep_time));
sleep(atoi(sleep_time));
printf("\n thread %d awakening\n",thr_self());
} compile 的時候記得要加 -lthread 以這個程式和上面 fork 中所舉的例子來做 比較可明顯的發現 thread 所佔用的 Memory 較少,另外需要注意的一點是,thread 和 fork 是可以結合使用的,結合使用時可分為兩種:一種是 fork 的時候將 parent process 全部複製;另一種是只有複製 parent process 中呼叫 fork() 的 thread。 |