pthread

 线程的优点:不占用资源,切换效率高,开销小,不存在通信.

pthread_create();创建一个线程 参数为 线程号 线程属性 线程函数 参数

pthread_join();该函数表有两个作用,一是回收线程资源,二是阻塞线程 但在循环结构中不推荐用此结构

pthread_detach();线程分离函数 自动回收线程资源 通常用于循环结构中

最好不要在线程中使用sleep函数,sleep是一个信号,针对进程而言的。

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

void delay()
{
	int i=10000,j;
	while(i>0)
	{
		j=10000;
		while(j>0)
		{
			j--;
		}
		i--;
	}
}//延迟函数
pthread_t tid1,tid2;
void *MyThread1(void *arg)//线程的返回值为void * 类型,参数也是void *
{
	int old;
	pthread_detach(pthread_self()/*回收当前线程的id*/);//线程分离  回收线程资源 自动回收
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&old);//设置取消类型,默认为可以被取消,在这里设置为立即取消
	printf("MyThread1\n");
	delay();              //最好不要在线程中使用sleep函数,sleep是一个信号,针对进程而言的。
	pthread_exit((void *)100); //线程的自己退出  ,里面的参数100传到底下的status
}
void *MyThread2(void *arg)//线程的返回值为void * 类型,参数也是void *
{
	printf("%s\n",(char *)arg); //类型转换
	pthread_cancel(tid1);  //取消上面一个线程,加上线程号
}
int main()
{
	int ret;
	char *ptr="helloworld";
	ret=pthread_create(&tid1,NULL,MyThread1,NULL);//线程号(要取地址),线程属性,线程函数,参数
	if(ret!=0)
	{
		perror("pthread_create");
		exit(1);  //进程的退出方式
	}
	ret=pthread_create(&tid2,NULL,MyThread2,(void *)ptr);//线程号(要取地址),线程属性,线程函数,参数
	if(ret!=0)
	{
		perror("pthread_create");
		exit(1);
	}
	void *status;  //线程的状态
	pthread_join(tid1,&status);
//回收的是哪个资源,线程的状态。//1、阻塞等待线程结束   2、回收线程资源(回收的是线程运行中堆和栈上分配的资源)
	printf("thread1 exit with%d\n",(int)status);
	pthread_join(tid2,&status);
	//循环里不可以用pthread_join因为它是阻塞的(不好使用时可以使用线程分离。)
	return 0;
}

猜你喜欢

转载自blog.csdn.net/tmh_15195862719/article/details/81544171