linux系统、网络等开发-07

工作需要,和大家共同学习总结。(学习的内容为传智播客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,失败返回错误号

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值