linux高编线程-------线程的创建,终止
生活随笔
收集整理的這篇文章主要介紹了
linux高编线程-------线程的创建,终止
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Q: what is thread ??
A:一個正在運行的函數----是運行函數咯----多線程共享內存空間咯
posix線程是一套標準,而不是實現
線程標識: pthread_t 類型不確定:結構體?or指針?or整型數,想啥是啥,可以自己定義咯
lhh@lhh:~$ ps axm lhh@lhh:~$ ps ax -L // LWP進程就是容器 ?內部裝載線程
函數:
int pthread_equal(pthread_t t1, pthread_t t2);//比較兩個線程是否相同;相同返回非0 否則返回0 pthread_t pthread_self(void); //返回當前線程標識;?
1.創建一個線程:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);參數1:回填線程表示
參數2:線程的屬性:常用NULL
參數3:函數指針 ----兄弟線程
參數4:兄弟線程的參數
返回值:成功返回0;失敗直接返回error number
2.線程的終止:
? ? ? 3種方式:1)線程從啟動例程返回,返回值就是線程的退出碼
? ? ? ? ? ? ? ? ? ? ? 2)線程可以被同一進程中的其他線程取消
? ? ? ? ? ? ? ? ? ? ? 3)線程調用pthread_exit()函數
void pthread_exit(void *retval);//線程終止 int pthread_join(pthread_t thread, void **retval);//線程收尸 成功返回0,錯誤返回error number **retval只收尸不關心狀態3.棧的清理:
//鉤子函數 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!休息休息,下節繼續!
?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);//取消線程:正在運行的線程先取消再收尸?
轉載于:https://www.cnblogs.com/muzihuan/p/4694662.html
總結
以上是生活随笔為你收集整理的linux高编线程-------线程的创建,终止的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js调试工具console详解
- 下一篇: 在 OS X 中使用 OpenResty