本文最后更新于2022年11月09日,已超过906天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!
您阅读这篇文章共耗时:
目录
一、线程的概念
特点
注意
Linux内核不提供线程,由线程库来实现。
二、线程的创建
#
int ( thread, const attr, void ()(void ), void arg);
成功返回0pthread_create 线程属性,失败时返回错误码
thread 线程对象
attr 线程属性,NULL代表默认属性
线程执行的函数
arg 传递给的参数 ,参数是void * ,注意传递参数格式,
注意事项:1. 主进程的退出,它创建的线程也会退出。
线程创建需要时间,如果主进程马上退出,那线程不能得到执行
三、线程的结束
#
void (void *retval);
结束当前线程
retval可被其他线程通过获取
线程私有资源被释放
获取线程的id
通过函数的第一个参数;通过在线程里面调用函数
四、线程间参数传递:(重点难点)
.c:8:5: error: use of void
printf("input arg=%d\n",(int)*arg);
通过地址传递参数,注意类型的转换值传递,这时候编译器会告警pthread_create 线程属性,需要程序员自己保证数据长度正确
#if 1
#include
#include
#include
void *testThread(void *arg){
printf("This is a thread test,pid=%d,tid=%lu\n",getpid(),pthread_self());
// return NULL;
printf("input arg=%d\n",*(int*)arg);//(int)arg
pthread_exit(NULL);
printf("after pthread exit\n");
}
int main(){
pthread_t tid;
int ret;
int arg = 5;
ret = pthread_create(&tid,NULL,testThread,(void *)&arg);//(void*)arg
printf("This is main thread,tid=%lu\n",tid);
sleep(1);
}
#endif
#if 0
#include
#include
#include
int *testThread(char *arg){
printf("This is a thread test pid = %d tid = %lu\n",getpid(),pthread_self());
pthread_exit(NULL);
printf("after pthread exit");
}
int main(){
pthread_t tid;
int ret;
ret = pthread_create(&tid,NULL,(void*)testThread,NULL);
printf("This is main Thread pid = %d tid = %lu\n",getpid(),tid);
sleep(1);
}
#if 1
#include
#include
#include
void *testThread(void *arg){
printf("This is a thread test,pid=%d,tid=%lu\n",getpid(),pthread_self());
// return NULL;
printf("input arg=%d\n",*(int*)arg);//(int)arg
pthread_exit(NULL);
printf("after pthread exit\n");
}
int main(){
pthread_t tid[5];
int ret,i;
int arg = 5;
for(i = 0;i < 5;i++){
ret = pthread_create(&tid[i],NULL,testThread,(void *)&i);//(void*)arg
printf("This is main thread,tid=%lu\n",tid[i]);
}
sleep(1);
}
五、线程的回收: 使用 函数:
#
int ( thread, void **retval);
注意: 是阻塞函数,如果回收的线程没有结束,则一直等待
程序:
#include #include #include void *func(void *arg){ printf("This is child thread\n"); //sleep(1); sleep(5); pthread_exit("thread return"); } #if 0 int main() { pthread_t tid; void *retv; pthread_create(&tid,NULL,func,NULL); pthread_join(tid,&retv); printf("thread ret=%s\n",(char*)retv); sleep(1); } #endif #if 1 int main(){ pthread_t tid[5]; void *retv; int i; for(i=0;i [1]: https://xuan.ddwoo.top/index.php/archives/207/ 本文来自投稿,不代表本站立场,如若转载,请注明出处:http://xuan.ddwoo.top/index.php/archives/210/