工作需要,和大家共同学习总结。(学习的内容为传智播客linux服务器开发二、三部分)
线程
1、线程共享全局变量,进程不共享全局变量,需要借助mmap
#include<unistd.h>
#include<cstdlib>
#include<iostream>
#include<sys/wait.h>
#include<fcntl.h>
#include<string>
#include<sys/mman.h>
#include<pthread.h>
#include <string.h>
using namespace std;
int var=100;
void * thread_func(void * arg){
var=200;
cout<<"IN thread:thread id="<<pthread_self()<<endl;
return NULL;
}
int main(int argc,char * argv[]){
pthread_t tid;
int ret;
cout<<"IN Main:thread id="<<pthread_self()<<endl;
cout<<"before thread,var="<<var<<endl;
ret=pthread_create(&tid,NULL,thread_func,NULL);
if(ret!=0){
perror("pthread_create error");
exit(1);
}
sleep(1);
cout<<"IN Main2:thread id="<<pthread_self()<<endl;
cout<<"after thread,var="<<var<<endl;
return 0;
}
2、线程退出pthread_exit,对应进程退出exit()
3、pthread_join 阻塞等待线程退出,获取线程退出状态。(回收pcb,获取退出状态,可以设置NULL,不关心退出状态)
4、pthread_detach 让线程分离,自动退出,无PCB残留
5、杀死线程pthread_cancel对应进程中的kill,成功0,失败返回错误号