天天看点

线程基础概念及pthread_cancel的使用

一、进程

1.进程有独立的地址空间

2.进程在创建时都会创建一个task_struct结构体

3.每个进程都会参与内核调度,相互间不会影响

二、线程

1.因为进程在切换时系统开销大,所以很多操作系统引入了轻量级进程LWP-线程

2.同一进程中的线程共享相同的地址空间,所以线程通常是指共享相同地址空间的多个任务

三、线程共享和和私有的资源

共享资源:

1.可以执行的命令

2.用户ID,用户组ID

3.静态数据

4.当前的工作目录

5.进程中打开的文件描述符

私有资源:

1.线程ID

2.pc(程序计数器)和相关的寄存器

3.堆栈,错误号,优先级,执行的状态和属性

四、程序demon

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function1(void *arg);
void *thread_function2(void *arg);

int main(int argc, const char *argv[])
{
    //声明线程id
	pthread_t tid1, tid2;
	int ret;
	void *retval1 = NULL; 
	void *retval2 = NULL; 
	
	//创建线程tid1
	ret = pthread_create(&tid1, NULL, thread_function1, NULL);
	if(0 != ret){
		perror("pthread_create 1");
		exit(EXIT_FAILURE);
	}
	printf("create thread 1 successful\n");

    //创建线程tid2
	ret = pthread_create(&tid2, NULL, thread_function2, &tid1);
	if(0 != ret){
		perror("pthread_create 2");
		exit(EXIT_FAILURE);
	}
	printf("create thread 2 successful\n");

    //函数pthread_join用来等待线程1的结束
	ret = pthread_join(tid1, &retval1);
	if(0 != ret){
		perror("pthread_join");
		exit(EXIT_FAILURE);
	}
	if(PTHREAD_CANCELED == retval1){
		printf("thread 1 was canceled by thread 2\n");
	}

     //函数pthread_join用来等待线程2的结束
	ret = pthread_join(tid2, &retval2);
	if(0 != ret){
		perror("pthread_join");
		exit(EXIT_FAILURE);
	}
	return 0;
}

void *thread_function1(void *arg){
	printf("Starting thread 1\n");
	while(1){
		printf("hello thread 1\n");
		sleep(1);
	}
	printf("Exiting thread 1\n");
	return NULL;
}

void *thread_function2(void *arg){
	int ret;
	printf("Starting thread 2\n");
	sleep(3);//3秒后取消线程1的运行
	ret = pthread_cancel(*((pthread_t *)arg));
	if(0 != ret){
		perror("pthread_cancel");
		pthread_exit(NULL);
	}
	printf("Exiting thread 2\n");
	return NULL;
}
           

运行结果:

线程基础概念及pthread_cancel的使用

继续阅读