linux中线程ID与进程ID

来源:互联网 发布:linux自动挂载硬盘 编辑:程序博客网 时间:2024/06/05 17:38

这篇博客主要是想通过线程ID和进程ID来说明进程和线程之间的关系,说明比较简单,直接上代码。代码也容易理解。

#include<pthread.h>#include<sys/types.h>#include<iostream>#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/syscall.h>#define gettid() syscall(_NR_gettid)using namespace std;void *print1(void *arg)//一个线程{for(int i = 0; i < 10; ++i){cout<<"print1 function!"<<endl;sleep(2);}cout<<"pthread_self() in thread1:"<< pthread_self()<<endl;cout<<"getpid() in thread1:"<<getpid()<<endl;}void *print2(void *arg)//一个线程{for(int i = 0; i < 10; ++i){cout<<"print2 function!"<<endl;sleep(1);}cout<<"pthread_self() in thread2:"<< pthread_self()<<endl;cout<<"getpid() in thread2:"<<getpid()<<endl;}int main()//主线程{pthread_t pid1,pid2;int err = 0;err = pthread_create(&pid1, NULL, print1, NULL);if(err){cerr<<"error in create thread1!"<<endl;exit(1);}cout<< pid1<<endl;//获取的是线程print1的线程IDerr = pthread_create(&pid2, NULL, print2, NULL);if(err){cerr<<"error in create thread2!"<<endl;exit(1);}cout<<pid2<<endl;//获取的是线程print2的线程IDcout << "getpid() in main :" << getpid() << endl;cout<<"pthread_self() in main:"<< pthread_self()<<endl;pthread_join(pid1, NULL);pthread_join(pid2, NULL);return 0;}//整个程序是一个进程(process),这三个线程(thread)都包含在同一个进程(process)中,其中mian是主线程,其他的print1和print2都是线程

执行结果


这整个程序中有三个线程:main主线程、print1和print2两个线程,这三个线程构成了同一个进程。通过getpid()分别在三个线程中获取到的进程ID都是25251,说明他们同属于一个进程。但是使用pthread_self()函数分别在三个线程中打印出的线程不一样说明了它们是三个不同的线程。

pthread_self()函数返回一个线程描述符(相当于上一节的文件描述符)。

getpid()函数返回进程描述符(相当于上一节的文件描述符)。

pthread_create函数的返回值仅仅是标示线程创建是否成功,如果返回值为0说明创建成功;如果返回值为非0说明创建失败。