Linux操作系统实验 | 第二章 | 实验二 线程共享进程中的数据

Author : STU_Lary

1. 实验说明

了解线程与进程之间的数据共享关系。创建一个线程,在线程中更改进程中的数据

2. 解决方案

在进程中定义共享数据,在线程中直接引用并输出该数据

3. 实验步骤

  1. 打开终端创建.c文件
终端输入 touch [文件名]

在这里插入图片描述

创建成功

在这里插入图片描述

  1. 对代码进行编写

在这里插入图片描述

  1. 生成可执行文件
终端输入 gcc exp2.c -o exp2 -lpthread

因为pthread库不是Linux系统的库,所以在进行编译的时候要加上-lpthread,否则编译通不过。

生成成功

在这里插入图片描述

  1. 执行文件

终端输入 ./exp2

​ 输出结果如下图所示:

4. 实验代码

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
 
static int shdata = 4;
 
void *create(void *arg)	
{
    
    	
	printf("new pthread ...\n");
	printf("shared data = %d\n",shdata);
	return (void *)0;
}
 
int main()
{
    
    
	pthread_t l;
	/*
		pthread_create函数返回0表示成功,非0表示失败
	*/
	//创建线程失败
	if(pthread_create(&l,NULL,create,NULL))
	{
    
    
		//打印失败提示信息
		printf("create pthread failed\n");
		//返回-1
		return -1;
	}
	else
	{
    
    
		//休眠一段时间
		sleep(1);
		//打印创建线程成功信息
		printf("create pthread successfully\n");

		printf("And shared data = %d\n \n",shdata);
		return 0;
	}
 
}

猜你喜欢

转载自blog.csdn.net/weixin_53249168/article/details/128385384