linux 2.6有真正的线程么,Linux 2.6内核下线程模型的改变

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的移植提供了方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值