分类: LINUX
2008-06-26 19:36:00
Linux内核2.6引入了新的线程模型,除了管理线程的能力大大提高,对于线程分组等管理方式也发生了改变,线程已经成为真正意义上的线程,线程用于了自己ID.(这种线程库好像是 Native Posix Thread Library 即NPTL)
下面这段代码在linux2.4和linux2.6上产生不同的结果:
=======================================================
#include
#include
#include
#include
#include
#include
#include
#include
#include
static inline _syscall0(int,gettid)
void task1(int *counter);
void task2(int *counter);
void cleanup(int counter1, int counter2);
int g1 = 0;
int g2 = 0;
int main(void) {
printf("PID = %d \n", getpid());
printf("PPID = %d \n", getppid());
pthread_t thrd1, thrd2;
int ret;
ret = pthread_create(&thrd1, NULL, (void*(*)(void*))task1, (void*)&g1);
if (ret) {
perror("pthread_create: task1");
exit(EXIT_FAILURE);
}
ret = pthread_create(&thrd2, NULL, (void*(*)(void*))task2, (void*)&g2);
if (ret) {
perror("pthread_create: task2");
exit(EXIT_FAILURE);
}
printf("threads created: [%d, %d]\n", thrd1, thrd2);
pthread_join(thrd2, NULL);
pthread_join(thrd1, NULL);
cleanup(g1, g2);
exit(EXIT_SUCCESS);
}
void task1(int *counter) {
printf("TASK1 PID = %d \n", getpid());
printf("TASK1 PPID = %d \n", getppid());
printf("TASK1 thread ID = %d \n", gettid());
while (*counter < 5) {
printf("task1 count: %d\n", *counter);
(*counter)++;
sleep(1);
}
}
void task2(int *counter) {
printf("TASK2 PID = %d \n", getpid());
printf("TASK2 PPID = %d \n", getppid());
printf("TASK1 thread ID = %d \n", gettid());
while (*counter < 5) {
printf("task2 count: %d\n", *counter);
(*counter)++;
sleep(1);
}
}
void cleanup(int counter1, int counter2)
{
int i;
printf("total iterations: %d\n", counter1 + counter2);
}
======================================================
在2。4下面的运行结果:
PID = 9862
PPID = 846
threads created: [8194, 16387]
TASK1 PID = 9864
TASK1 PPID = 9863
TASK1 thread ID = 9864
task1 count: 0
TASK2 PID = 9865
TASK2 PPID = 9863
TASK1 thread ID = 9865
task2 count: 0
task1 count: 1
task2 count: 1
task1 count: 2
task2 count: 2
task1 count: 3
task2 count: 3
task1 count: 4
task2 count: 4
total iterations: 10
-----------------------
在2.6下的运行结果为:
PID = 30015
PPID = 6786
threads created: [-151106640, -161596496]
TASK1 PID = 30015
TASK1 PPID = 6786
TASK1 thread ID = 30016
task1 count: 0
TASK2 PID = 30015
TASK2 PPID = 6786
TASK1 thread ID = 30017
task2 count: 0
task1 count: 1
task2 count: 1
task1 count: 2
task2 count: 2
task1 count: 3
task2 count: 3
task1 count: 4
task2 count: 4
total iterations: 10
------------------------------
由此可见,在linux2。6下,同一进程所创建的线程将具有相同的进程ID,但具有不同的线程ID,这样就真正兼容POSIX的线程。对其他平台上程序向linux的移植提供了方便。