linux高编线程-------线程的创建,终止
Q: what is thread ??
A:一個(gè)正在運(yùn)行的函數(shù)----是運(yùn)行函數(shù)咯----多線程共享內(nèi)存空間咯
posix線程是一套標(biāo)準(zhǔn),而不是實(shí)現(xiàn)
線程標(biāo)識(shí): pthread_t 類型不確定:結(jié)構(gòu)體?or指針?or整型數(shù),想啥是啥,可以自己定義咯
lhh@lhh:~$ ps axm lhh@lhh:~$ ps ax -L // LWP進(jìn)程就是容器 ?內(nèi)部裝載線程
函數(shù):
int pthread_equal(pthread_t t1, pthread_t t2);//比較兩個(gè)線程是否相同;相同返回非0 否則返回0 pthread_t pthread_self(void); //返回當(dāng)前線程標(biāo)識(shí);?
1.創(chuàng)建一個(gè)線程:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);參數(shù)1:回填線程表示
參數(shù)2:線程的屬性:常用NULL
參數(shù)3:函數(shù)指針 ----兄弟線程
參數(shù)4:兄弟線程的參數(shù)
返回值:成功返回0;失敗直接返回error number
2.線程的終止:
? ? ? 3種方式:1)線程從啟動(dòng)例程返回,返回值就是線程的退出碼
? ? ? ? ? ? ? ? ? ? ? 2)線程可以被同一進(jìn)程中的其他線程取消
? ? ? ? ? ? ? ? ? ? ? 3)線程調(diào)用pthread_exit()函數(shù)
void pthread_exit(void *retval);//線程終止 int pthread_join(pthread_t thread, void **retval);//線程收尸 成功返回0,錯(cuò)誤返回error number **retval只收尸不關(guān)心狀態(tài)3.棧的清理:
//鉤子函數(shù) void pthread_cleanup_push(void (*routine)(void *),void *arg);void pthread_cleanup_pop(int execute);eg:
#include <pthread.h> #include <string.h> static void *func(void *p) {puts("Thead is working!");pthread_exit(NULL); }int main() {pthread_t tid;int err;puts("Begin !");err = pthread_create(&tid,NULL,func,NULL);if(err){ fprintf(stderr,"%s",strerror(err));exit(1);} pthread_join(tid,NULL);puts("End !");exit(0); } View CodeOK!休息休息,下節(jié)繼續(xù)!
?eg:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h>void *cleanup_func(void *p) {puts(p); }void *func(void *p) {puts("Thead is working !");pthread_cleanup_push(cleanup_func , "cleanup:1");pthread_cleanup_push(cleanup_func , "cleanup:2");pthread_cleanup_push(cleanup_func , "cleanup:3");pthread_cleanup_pop(1);pthread_cleanup_pop(0);pthread_cleanup_pop(1);pthread_exit(NULL); }int main() {pthread_t tid ;int err ;puts("Begin !");err = pthread_create(&tid,NULL,func,NULL);if(err){ fprintf(stderr,"%s",strerror(err));exit(1);} pthread_join(tid,NULL);exit(0); } View Code4.線程取消
int pthread_cancel(pthread_t thread);//取消線程:正在運(yùn)行的線程先取消再收尸?
轉(zhuǎn)載于:https://www.cnblogs.com/muzihuan/p/4694662.html
總結(jié)
以上是生活随笔為你收集整理的linux高编线程-------线程的创建,终止的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: js调试工具console详解
- 下一篇: 在 OS X 中使用 OpenResty