日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > linux >内容正文

linux

linux高编线程-------线程的创建,终止

發(fā)布時(shí)間:2025/7/14 linux 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux高编线程-------线程的创建,终止 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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 Code

OK!休息休息,下節(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 Code

4.線程取消

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。