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;
}