Linux线程

1.线程的概念

LWP:light weight process 轻量级的进程,本质任然是进程(在Linux环境下)

进程:独立地址空间,拥有PCB

线程:也有PCB,但没有独立的地址空间(共享)

区别:在于是否共享地址空间;独居(进程), 合租(线程)

Linux下:线程:最小的执行单位

进程:最小分配资源单位,可看成是只有一个线程的进程

一个进程内部可以有多个线程,默认情况下一个进程只有一个线程

内核实现都是通过clone实现的

线程也有自己的PCB

查看LWP号:ps -Lf pid 查看指定线程的lwp号

2.线程共享资源

1.文件描述符表

2.每种信号的处理方式

3.当前工作目录

4.用户ID和组ID

5.内存地址空间(.text 、.data、 .bss、 heap、 共享库)

3.线程非共享资源

1.线程id

2.处理器现场和栈指针(内核栈)

3.独立的栈空间(用户空间栈)

4.errno变量 

        获取错误码对应的错误信息

        char* strerror(int errnum);

5.信号屏蔽字

6.调用优先级

4.线程的优缺点

优点:提高并发性,占用资源小,通信方便

缺点:调试困难,库函数不稳定,对信号支持不好

5.线程的操作函数

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

 thread:线程的id,传出参数

arrr: 代表线程的属性

第三个参数 函数指针 , void* func(void*) 

arg: 线程执行函数的参数

返回值:成功返回0,失败返回errno

编译的时候需要加pthread库

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pthread.h>

void* thr(void* arg)
{
	printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	printf("I am a main thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	sleep(1);
	exit(0);
}

 


SRC = $(wildcard *.c)
SRC += $(wildcard ./src/*.c)

OBJ = $(patsubst %.c, %.o, $(SRC))

ALL:app

app:$(OBJ)
	gcc -o $@ -I ./include $(OBJ) -lpthread

%.o:%.c
	gcc -c $< -I ./include -o $@

test:
	echo $(SRC)
	echo $(OBJ)

.PHONY:clean all

clean:
	-@rm -f *.o app ./src/*.o

线程退出函数 pthread_exit

线程退出注意事项:

        在线程中使用pthread_exit

        在线程中使用return(主控线程return代表退出进程)

        exit代表退出整个进程

线程回收:阻塞等待回收

int pthread_join(pthread_t thread, void **retval);

        thread: 创建的时候传出的第一个参数

        retval:传出线程的退出信息

void* thr(void* arg)
{
	printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	sleep(5);
	return (void*)100;
	// pthread_exit(NULL);
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	void *ret = NULL;
	pthread_create(&tid, NULL, thr, NULL);
	printf("I am a main thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	pthread_join(tid, &ret);
	printf("ret = %d\n", (int*)ret);
	pthread_exit(NULL);
	exit(0);
}

void* thr(void* arg)
{
	printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	sleep(5);
	// return (void*)100;
	pthread_exit((void*)101);
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	void *ret = NULL;
	pthread_create(&tid, NULL, thr, NULL);
	printf("I am a main thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	pthread_join(tid, &ret);
	printf("ret = %d\n", (int*)ret);
	pthread_exit(NULL);
	exit(0);
}

 杀死线程:

int pthread_cancel(pthread_t thread);

        需要传入tid;

         返回值:失败返回errno,成功返回0

        被pthread_cancel杀死的线程,退出状态为PTHREAD_CANCELED

        #define PTHREAD_CANCELED ((void *) -1)

强行设置取消点:pthread_testcancel();

void* thr(void* arg)
{
	while (1)
	{
		printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
		sleep(1);
	}
	// return (void*)100;
	pthread_exit((void*)101);
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	void *ret = NULL;
	pthread_create(&tid, NULL, thr, NULL);
	printf("I am a main thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	
	sleep(3);
	pthread_cancel(tid);	// 杀死线程

	pthread_join(tid, &ret);
	printf("pthread exit ret = %d\n", (int*)ret);
	exit(0);
}

 

 线程分离:

此时不需要pthread_join回收资源

int pthread_detach(pthread_t thread);
void* thr(void* arg)
{
	printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	sleep(1);	
	printf("I am a thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	return NULL;
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	void *ret = NULL;
	int res = 0;
	pthread_create(&tid, NULL, thr, NULL);
	printf("I am a main thread, pid = %d, tid = %lu\n", getpid(), pthread_self());
	pthread_detach(tid); // 线程分离
	sleep(3);	
	
	if ((res = pthread_join(tid, &ret)) > 0)
	{
		printf("join err:%d, %s\n", res, strerror(res));
	}
	printf("pthread exit ret = %d\n", (int*)ret);
	exit(0);
}

 

int val = 100;

void* thr(void* arg)
{
	printf("I am a thread, tid = %lu, val = %d\n", pthread_self(), val); // 1003
	sleep(2);	
	val = 1001;
	printf("I am a thread, tid = %lu, val = %d\n", pthread_self(), val); // 1001
	return NULL;
}

int main(int argc, char* argv[])
{

	pthread_t tid;
	pthread_create(&tid, NULL, thr, NULL);
	pthread_detach(tid); // 线程分离
	printf("I am a main thread, tid = %lu val = %d\n", pthread_self(), val); //100
	val = 1003;
	sleep(5);	
	printf("I am a main thread, tid = %lu val = %d\n", pthread_self(), val); // 1001

	int ret = 0;
	if ((ret = pthread_join(tid, NULL)) > 0)
	{
		printf("join err:%d, %s\n", ret, strerror(ret));
	}

	exit(0);
}

线程共享全局变量 

线程id在进程内部是唯一的!

void* thr(void* arg)
{
	int num = (int )arg;
	printf("I am %d thread, self = %lu\n", num, pthread_self());
	return (void*)(100+num);
}

int main(int argc, char* argv[])
{

	pthread_t tid[5];
	int i = 0;
	for (size_t i = 0; i < 5; i++)
	{
		pthread_create(&tid[i], NULL, thr, (void*)i);
	}
	for (size_t i = 0; i < 5; i++)
	{
		void* ret = NULL;
		pthread_join(tid[i], &ret);
		printf("i = %d, ret = %d\n", i, (int)ret);
	}
	
	exit(0);
}

 进程属性控制:

int pthread_attr_init(pthread_attr_t *attr);      // 初始化线程属性
int pthread_attr_destroy(pthread_attr_t *attr);   // 销毁线程属性

// 设置属性分离态
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate); 

        attr: init初始化的属性

        detachstate:

                PTHREAD_CREATE_DETACHED        线程分离

                PTHREAD_CREATE_JOINABLE        允许回收(默认)

void* thr(void* arg)
{
	printf("I am thread, self = %lu\n", pthread_self());
	return NULL;
}

int main(int argc, char* argv[])
{

	pthread_attr_t attr;
	pthread_attr_init(&attr); // 初始化属性

	pthread_t tid;
	pthread_create(&tid, &attr, thr, NULL);

	int ret = 0;
	if ((ret = pthread_join(tid, NULL)) > 0)
	{
		printf("join err = %d, %s\n", ret, strerror(ret));
	}
	pthread_attr_destroy(&attr);//销毁属性
	
	exit(0);
}

 

void* thr(void* arg)
{
	printf("I am thread, self = %lu\n", pthread_self());
	return NULL;
}

int main(int argc, char* argv[])
{

	pthread_attr_t attr;
	pthread_attr_init(&attr); // 初始化属性
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // 设置属性分离

	pthread_t tid;
	pthread_create(&tid, &attr, thr, NULL);

	int ret = 0;
	if ((ret = pthread_join(tid, NULL)) > 0)
	{
		printf("join err = %d, %s\n", ret, strerror(ret));
	}
	pthread_attr_destroy(&attr);//销毁属性
	
	exit(0);
}

查看pthread库版本:

 

 6.线程使用注意事项

1.主线程退出其他线程不退出,主线程应调用pthread_exit

2.避免僵尸线程:

        pthread_join

        pthread_detach

        pthread_create指定分离属性

        被join线程可能在join函数返回前就释放完自己的所有内存资源,所有不应当返回被回收线程栈中的值 

3.malloc和mmap申请的内存可以被其他线程释放

4.应避免在多线程模型中调用fork除非,马上exec, 子进程中只有调用fork的线程存在,其他线程在子线程中均pthread_exit

5.信号的复杂语义很难和多线程共存,应避免在多线程引入信号机制

创建多少个线程?

        cpu核数*2+2 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值