线程和进程的区别
1.进程在切换时系统开销大
2.很多操作系统引入了轻量级进程LWP
3.同一进程中的线程共享相同的地址空间
4.Linux不区分进程、线程
特点
1.通常线程指的是共享相同地址空间的多个任务
2.线程a中的变量线程b也可以访问,他们时共享的
Linux线程库
pthread线程库中提供了如下基本操作
1.创建线程
pthread_create,成功时返回0
注意:
1.主进程退出,它创建的线程也会退出。
2.线程创建需要时间,如果主进程马上退出,那线程不能得到执行。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *testThread(void*arg)
{
printf("This is a thread test\n");
printf("input arg=%d\n",*(int * )arg);
pthread_exit(NULL); //线程的退出
return NULL;
}
int main( )
{
pthread_t tid;
int ret;
int arg = 5;
ret = pthread_create(&tid,NULL,testThread,(void*)&arg);
}
2.回收线程
线程回收:pthread_join
成功时返回0,thread要回收的对象,调用线程阻塞直到thread结束
注意:
pthread_join 是阻塞函数,如果回收的线程没有结束,则一直等待
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *func(void *arg)
{
printf("this is child thread\n");
sleep(5);
pthread_exit("thread return ");
}
int main(){
pthread_t tid[5];
void *retv;
for(i=0;i<5;i++)
{
pthread_create(&tid[i],NULL,func,NULL);
}
for(i=0;i<5;i++){
pthread_join(tid[i],&retv);
printf("thread ret=%s\n",retv);
}
sleep(1);
}
3.结束线程
pthread_exit
1.结束当前线程
2.线程私有资源被释放
4.参数传递
编辑错误,错误原因是void * 类型指针不能直接用*取值(*arg),因为编译不知道数据类型。
解决方法:转换为指定的指针类型再用*取值 比如*(int * )arg
注意:
1.通过地址传递参数,注意类型的转换
2.值传递,这时候编译器会报警,需要程序员自己保证数据长度正确
数组越界:栈被破坏了
5.线程分离
pthread_detach 线程主动与主控线程断开关系,线程结束后不会产生僵尸线程。
设置属性
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *func(void *arg)
{
pthread_detach(pthread_self());
printf("this is child thread\n");
sleep(5);
pthread_exit("thread return ");
}
int main(){
pthread_t tid[5];
void *retv;
int i;
pthread_attr_attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
for(i=0;i<5;i++)
{
pthread_create(&tid[i],NULL,func,NULL);
// pthread_detach(tid);
}
}
sleep(1);
}
6.线程取消
int pthread_cancel(pthread_t thread)
线程的取消要有去取消点才可以,不是说取消就取消,线程的取消点主要是阻塞的系统调用
7.线程的清理
void pthread_cleanup_push(void (*))