- 線程的概念
進程與線程內核實現 通過函數clone實現的
ps -Lf pid
-
Linux內核線程實現原理
同一個進程下的線程,共享該進程的內存區, 但是只有stack區域不共享。 -
線程共享資源
a.文件描述符表
b.每種信號的處理方式
c.當前工作目錄
d.用戶id和組id -
線程非共享資源
a.線程id
b.處理器現場和棧指針(內核棧)
c.獨立的棧空間(用戶空間棧)
d.errno變量
e.信號屏蔽字
f.調度優先級 -
在主線程里面執行return, 相當于整個進程退出了
-
小技巧
set -o vi 相當于把當前shell,弄成了 vi 編輯器模式
7.創建一個線程
man pthread_create
#include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);Compile and link with -pthread.
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>void* func(void *arg) {printf("I am a common thread, pid is %d, tid is %ld\n", getpid(), pthread_self());pthread_exit(NULL);
}int main() {pthread_t tid;pthread_create(&tid, NULL, func, NULL);printf("I am a man thread, pid is %d,create tid is %ld\n", getpid(), tid);printf("I am a man thread, pid is %d, tid is %ld\n", getpid(), pthread_self());pthread_exit(NULL);return 0;
}經測試,主線程使用pthread_exit函數,可以等待子線程的退出。
線程退出函數:
8.線程回收函數:
int pthread_join(pthread_t thread, void **retval);
參數介紹:thread: 表示要回收的線程(創建線程時候傳出的第一個參數)retval:要回收的線程的退出信息
線程回收也是阻塞等待回收
代碼案例:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>void* func(void *arg) {printf("I am a common thread, pid is %d, tid is %ld\n", getpid(), pthread_self());// pthread_exit((void *)100);return (void*)(100);
}int main() {pthread_t tid;pthread_create(&tid, NULL, func, NULL);printf("I am a man thread, pid is %d,create tid is %ld\n", getpid(), tid);printf("I am a man thread, pid is %d, tid is %ld\n", getpid(), pthread_self());void * ret;pthread_join((tid), &ret);printf("join tid return value is %d\n", (int)ret);return 0;
}