计算机操作系统第二次实验——线程共享进程中的数据

供大家交流学习,最好自己动手做,这样才有最深切的体会。


1.实验目的

利用pthread_create()函数创建一个线程,在线程中更改进程中的数据 ,了解线程与进程之间的关系。


2.实验软硬件环境
  • 安装Windows XP的计算机
  • VirtualBox软件,以及在其上安装的Ubuntu虚拟机

3.实验内容

    在Linux下利用线程创建函数pthread_create()创建一个线程,在线程中更改进程中的数据,并分别在线程和main函数里输出线程的tid,将结果输出到终端。

    pthread_create()、sleep()函数介绍:

  • int pthread_create(pthread_t *restrict tidp,   const   pthread_attr_t *restrict attr, void *(*start_rtn)(void),  void *restrict arg) 创建线程,若成功则返回0,否则返回出错编号第一个参数为指向线程标识符的指针。第二个参数用来设置  线程属性。第三个参数是线程运行函数的起始地址。最后一个参数是运行函数的参数。另外,在编译时注意加上-lpthread参数,以调用链接库。因为pthread并非Linux系统的默认库 。
  • unsigned sleep(unsigned milliseconds)  执行挂起一段时间,参数为无符号整型变量,单位是毫秒。

4.实验程序及分析

实验程序:

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

static int i = 1;
//i是全局变量

void *create(void *arg)	
{	//函数名前加*,说明返回的是一个指向函数的指针
	printf("new pthread ...\n");
	printf("shared data = %d\n",i);
	printf("my tid is %ld\n",(unsigned long int)pthread_self());
	//在线程中通过pthread_self()函数返回自己的pid,类型为无符号长整数(unsigned long int),在printf中用%ld格式化输出。
	i=2;
	//修改全局变量i的值
	return (void *)0;
}

int main()
{
	pthread_t l;
	//l用来存储线程的tid,数据类型pthread_t是无符号长整数(unsigned long int)
	i=3;
	//修改全局变量i的值	
	if(pthread_create(&l,NULL,create,NULL))
	{	//pthread_create()函数需要四个参数,其中第一个是存线程tid的地址&l,并且会向l返回所创建线程的tid,第三个变量是线程程序的起始地址,即指向线程程序的指针
		//pthread_create()函数成功则返回0,否则返回出错编号
		printf("create pthread failed\n");
		return -1;
	}
	else
	{
		sleep(1);
		printf("create pthread successfully\n");
		printf("And shared data = %d\n return tid = %ld\n",i,(unsigned long int)l);
		//输出main中i的值以及pthread_create()函数所创建线程的ID——l的值
		return 0;
	}


	int n = sizeof(pthread_t);
	printf("the pthread_t has %d Byte\n",n);



}

终端结果:


分析:

线程共享进程的地址空间,所以线程对资源的改变会反映到进程中,故i之前为3,进入线程后被改为2,在进程中输出为2.并且线程自己返回的tid与pthread_create()函数返回到l的值是一样的。


5.实验截图




6.实验心得体会

    通过这次实验,我了解到如何在Linux下创建线程以及线程与进程间的关系,线程共享进程的地址空间,线程对资源的改变会影响到进程,线程能且只能分配到进程中的资源。














发布了47 篇原创文章 · 获赞 28 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41122796/article/details/80294206