thread线程是linux的重要概念。线程不能独立存在,必须在进程中存在。一个进程必须有一个线程,如果进程中没有创建新线程,进程启动后本身就有一个线程。使用getpid、getppid获取进程的进程ID和父进程ID。使用pthread_self获取到当前线程的ID。
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>int main( int argc, char *argv[] ){printf("parent pid %d, pid:%d, thread id:%ld\n",getppid( ),getpid( ),pthread_self( ));return 0;
}
当前进程的父进程ID:2595,进程ID:26974,线程ID:139917979055872。
使用pthread_create函数可以创建新的线程。线程没有独立的PCB,所以使用的是进程的PCB。
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
thread 记录创建的线程的ID,attr新创建线程的属性,一般为NULL。
start_routine 线程启动函数,arg线程驱动函数的参数。
创建一个线程,输出线程的参数。参数是字符串“hello world ”。
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>void *thread_fun( void *argv){printf("thread_fun:%s\n",(char*)argv);printf("thread_fun:parent pid %d, pid:%d, thread id:%ld\n",getppid( ),getpid( ),pthread_self( ));return (void *)0;
}int main( int argc, char *argv[] ){printf("main begin\n");printf("main:parent pid %d, pid:%d, thread id:%ld\n",getppid( ),getpid( ),pthread_self( ));pthread_t tid;char *str = "hello world!"; pthread_create( &tid, NULL, thread_fun,(void *)str);sleep(1);printf("main end\n");return 0;
}