《linux 线程函数小结》由会员分享,可在线阅读,更多相关《linux 线程函数小结(5页珍藏版)》请在金锄头文库上搜索。
1、linux 线程函数小结由于主线程已经开始跑了,次线程还在使用串口打印需要一点时间,因此打印的都是重复的。12345678910111213141516171819202122232425262728#include pthread.h#include stdio.h#include stdlib.hstaticvoid* thread_function(void* arg )/ printf(%s %dn ,_FUNCTION_ , (int)arg );printf(%s %dn ,_FUNCTION_ , *(int*)arg );while(1);returnNULL;intmain(
2、intargc,constchar*argv)pthread_t tid10;inti;for(i = 0; i10 ; i+) /pthread_create(&tidi ,NULL, thread_function ,(void *) i );传送值的方法pthread_create(&tidi ,NULL, thread_function ,(void*) &i ); 传送地址的方法while(1)/printf(%sn,_FUNCTION_);/sleep(1);return0;1 查看线程的指令ps -eLf | grep thread ;2 线程不是先创建的先执行,是根据内核来决定
3、的先执行那个。3 可以在创建线程的时候增加延时,让每个线程依次执行,这样子大的log就是顺序执行的。看某个进程的资源top -p 4081线程回收,pthread_join ; 只调用pthread_exit 是不行的,只是退出线程,但是大小是没有变化的。pthread_join 是阻塞函数,因此可以将线程改为pthread_detach 改为detach属性,结束后自动释放资源的。20s之后线程的资源变小#include pthread.h#include stdio.h#include stdlib.hstatic void * thread_function(void * arg ) p
4、rintf(%s %dn ,_FUNCTION_ , (int)arg ); /printf(%s %dn ,_FUNCTION_ , *(int*)arg ); sleep(20); pthread_exit(I quitn); while(1); return NULL;int main(int argc, const char *argv) pthread_t tid10; int i; for(i = 0; i10 ; i+) pthread_create(&tidi ,NULL, thread_function ,(void *) i ); pthread_detach(tidi);
5、 /pthread_create(&tidi ,NULL, thread_function ,(void *) &i ); /sleep(1); /pthread_join 是阻塞函数,因此可以将线程改为pthread_detach 改为detach属性,pthread_exit结束后自动释放资源的。 /* int errno ; for(i = 0; i10 ; i+) errno = pthread_join(tidi ,NULL);if(errno = -1 ) perror(pthread_exit); return -1 ; */ while(1) /printf(%sn,_FUNCTION_); /sleep(1); return 0;