1.线程的实现方式
1.用户级线程
开销小,用户空间就可以创建多个。缺点是:内核无法感知用户级多个线程的存在,把其当作只有一个线程,所以只会提供一个处理器。
2.内核级线程
相对于用户级开销稍微大一点,可以利用多个处理器。
3.组合级线程
在不同平台Linux 中线程的实现:
Linux 实现线程的机制非常独特。从内核的角度来说,它并没有线程这个概念。Linux 把所有的线程都当做进程来实现。内核并没有准备特别的调度算法或是定义特别的数据结构来表征线程。相反,线程仅仅被视为一个与其他进程共享某些资源的进程。每个线程都拥有唯一隶属于自己的 task_struct,所以在内核中,它看起来就像是一个普通的进程(只是线程和其他一些进程共享某些资源,如地址空间)。
2.线程的使用
2.1线程库的接口—pthread函数
1)pthread_create
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
2)pthread_join
int pthread_join(pthread_t thread, void **retval);
3)pthread_exit
int pthread_exit(void *retval);