一个进程中的所有线程都可以访问该进程的组成部件。用同步机制防止多个线程查看到不一致的共享资源。
线程包含了表示进程内执行环境必须的信息,其中包括进程中标识线程的线程ID、一组寄存器、栈、调度优先级和策略、信号屏蔽字
、errno变量以及线程的私有数据。
进程的所有信息对该进程的所有线程都是共享的。
线程ID的数据类型是pthread_t数据类型,可以用下面的函数比较两个线程ID。
int pthread_equal( pthread_t tid1, pthread_t tid2);
线程可以通过调用pthread_self函数获得自身的线程ID。
#include <pthread.h>
pthread_t pthread_self( void )
在传统UNIX进程模型中,一个进程只有一个控制线程。我们可以通过pthread_create函数创建。
#include <pthread.h>
int pthread_create([pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void *restrict arg)
当成功返回后,tidp指向的内存单元被设置为新创建线程的线程ID。
attr参数用于保存不同的线程属性。
下面的实例打印进程ID、新的线程ID、初始线程ID:
[root@localhost apue]# gcc page290.c -l pthread [root@localhost apue]# ./a.out main thread: pid 1696 tid 3086464704 (oxb7f7b6c0) new thread: pid 1696 tid 3086461840 (oxb7f7ab90) [root@localhost apue]# cat page290.c #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 (ox%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid); } void * thr_fn(void *arg) { printids("new thread: "); return((void *)0); } int main(void) { int err; err = pthread_create(&ntid, NULL,thr_fn, NULL); if(err != 0) err_quit("can‘t create thread:%s\n",strerror(err)); printids("main thread:"); sleep(1); exit(0); }
原文:http://blog.csdn.net/huang2009303513/article/details/19575923