所有,
下面的代码来自"Unix环境中的高级编程",它创建一个新线程,并打印主线程和新线程的进程ID和线程ID.
在本书中,它表示在linux中,此代码的输出将显示两个线程具有不同的进程ID,因为pthread使用轻量级进程来模拟线程.但是当我在Ubuntu 12.04中运行此代码时,它有内核3.2,打印相同的pid.
那么,新的linux内核是否会改变pthread的内部实现?
#include "apue.h"
#include <pthread.h>
pthread_t ntid;
void printids(const char *s) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n",
s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *thread_fn(void* arg) {
printids("new thread: ");
return (void *)0;
}
int main(void) {
int err;
err = pthread_create(&ntid, NULL, thread_fn, NULL);
if (err != 0)
err_quit("can't create thread: %s\n", strerror(err));
printids("main thread: ");
sleep(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在kthread_create的定义中,任务被唤醒,是否有人知道这个任务在做什么?
struct task_struct *kthread_create
{
struct kthread_create_info create;
create.threadfn = threadfn;
create.data = data;
init_completion(&create.done);
spin_lock(&kthread_create_lock);
list_add_tail(&create.list, &kthread_create_list);
spin_unlock(&kthread_create_lock);
**wake_up_process(kthreadd_task);**
wait_for_completion(&create.done);
if (!IS_ERR(create.result)) {
struct sched_param param = { .sched_priority = 0 };
va_list args;
va_start(args, namefmt);
vsnprintf(create.result->comm, sizeof(create.result->comm),
namefmt, args);
va_end(args);
/*
* root may have changed our (kthreadd's) priority or CPU mask.
* The kernel thread should not inherit these properties.
*/
sched_setscheduler_nocheck(create.result, SCHED_NORMAL, ¶m);
set_cpus_allowed_ptr(create.result, cpu_all_mask);
}
return create.result;
}
Run Code Online (Sandbox Code Playgroud) 众所周知,kthreadd是一个内核线程,用于帮助其他人创建新的内核线程(kthread_create_list查看是否需要创建任何新的内核线程).
但我不明白为什么我们不使用create_kthread创建新的内核线程?我认为kthreadd没有任何区别.
请你给我一些建议.
谢谢你的大力帮助.
我必须实现内核级线程,但是在网上搜索时,我发现在 linux 中可以通过三种方法创建内核级线程:
在某处写到 linuxThreads 现在被放弃了。但是我找不到当前对 NPTL 和 kthread 的支持。此外,我找不到任何可以简单解释我如何使用其功能的来源。
哪个是当前支持和使用内核级线程的好库?
还请分享安装这些库并使用它们的任何资源?