C语言 Pthread的学习使用

Pthread是POSIX threads , 是线程的POSIX标准(POSIX是操作系统接口标准,为应用程序提供统一的接口标准)。

Unix , Linux , Mac OS都使用Pthread来管理线程。

PID是进程统一标识,PPID是父进程标识号。一个PID唯一地标识一个进程。一个进程创建新进程称为创建了子进程。

所有进程追溯其祖先最终都会落到进号为1的进程身上,这个进程叫做init进程,是内核自举后第一个启动的进程。

init进程扮演终结父进程的角色。因为init进程永远不会终止,所以系统总是可以确信它的存在,并在必要的时候以它为参照。

Linux中一个进程在内存里有三部分数据,就是“堆”、“栈”、“代码段”。

线程可以和同进程的其他线程共享数据,但拥有自己的栈空间。


1.线程的创建

#  pthread_create( ); pthread_join( ); pthread_t ; sleep( );

#include 
#include 
void thread()
{
	int i=0;
	for(i=0;i<=5;i++)
	{
		printf("this is thread %d\n",i);
	//	sleep();
	}
}
int main()
{
	pthread_t id;  //线程的标识符,unsigned long int.
	int ret,i=0;
	ret = pthread_create(&id,NULL,(void *)thread,NULL); 
	 /*
	  *	第一个参数是pthread_t 类型的指针。
	  *   	第二个参数用来设置线程属性。
	  * 	第三个参数线程运行函数的地址。
	  * 	第四个参数是运行函数的参数。
	  */
	if(ret!=0)    //  线程创建成功返回0
	{
		printf("To thread failed\n");
		exit(0);
	}
	for(i=0;i<=5;i++)
	{
		printf("This is main thread %d\n",i);
		sleep(1);  // 当前线程睡眠1秒。
	}
	pthread_join(id,NULL);
	// 将标识为id的线程加入当前线程。
	// 即等待该线程执行结束再恢复当前线程运行 
	return 0;
}

运行结果:

C语言 Pthread的学习使用_第1张图片

2.线程的终止

# pthread_exit(NULL);  pthread_self( ); 

#include 
#include 
void thread()
{
	int i=0;
	pthread_t mythread;
	for(i=0;i<=5;i++)
	{
		printf("this is thread %d\n",i);
		mythread = pthread_self();  // 返回当前线程id
		printf("my thread id is %ld\n",mythread);
	//	pthread_exit(NULL); // 终止当前线程	
	//	sleep();
	}
}
int main()
{
	pthread_t id,mythread;  //线程的标识符,unsigned long int.
	int ret,i=0;
	ret = pthread_create(&id,NULL,(void *)thread,NULL); 
	 /*
	  *	第一个参数是pthread_t 类型的指针。
	  *   	第二个参数用来设置线程属性,返回值需要为void类型。
	  * 	第三个参数线程运行函数的地址。
	  * 	第四个参数是运行函数的参数。
	  */
	if(ret!=0)    //  线程创建成功返回0
	{
		printf("To thread failed\n");
		exit(0);
	}
	for(i=0;i<=5;i++)
	{
		printf("This is main thread %d\n",i);
		sleep(1);  // 当前线程睡眠1秒。
	}
	printf("Main thread is %ld\n",pthread_self());
	pthread_join(id,NULL);
	// 将标识为id的线程加入当前线程。
	// 即等待该线程执行结束再恢复当前线程运行 
	return 0;
}
运行结果

C语言 Pthread的学习使用_第2张图片





附录:

上下文切换(context): 调度CPU时间片时,保存上一个使用者在寄存器,内存中的数据。

kill 命令:

kill  12345  //  杀死进程号为12345的进程

grep '122'  pthread.h   //在pthread.h文件中查找包含“122”的行

grep 'int main'  *.c  //显示当前目录下所有.c文件包含 int main 的行

df命令:

用来检查linux服务器的文件系统的磁盘空间占用情况。

comm file1 file2  //对比两个文件

comm -12 file1 file2 // 只显示两个文件中都出现的行

diff file1 file2 //  逐行对比,显示两个文件的不同

pstree命令:

允许用户查看系统内正在运行的各个进程之间的继承关系。

gcc 命令 

-o 为指定程序名。

-pthread  增加对pthread库的支持

-L 指定库文件的所在路径(非/lib/usr/lib/usr/local/lib,都需指定)

-l  为指定链接的库文件名

-c 只编译,不产生程序,用于编译库函数。

你可能感兴趣的:(C)