一【实验目的】
1.理解线程环境、线程的生命周期,
2.理解线程同步,掌握内核函数的基本用法。
3.支撑网络空间安全专业的专业核心能力、综合创新能力。
二【实验要求】
以下每个实验均要求:
1.“实验源代码”处:粘贴所编写的程序源码,务必添加关键语句的注释;
2.“实验结果”:截图(包括编写的程序和运行结果)粘贴到“实验结果”下方,截图需看到本人的名字及学号;
3.有“讨论”的题目,请务必认真回答;
三【实验内容】
5-1 编写一个多线程程序:要求主线程创建3个子线程, 3个子线程在执行时都修改一个它们的共享变量,观察共享变量的值,看看可以得出什么结论。
【源程序】
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
int x=0;
void *thread1(void *arg){
x=x+1;
printf("pthread1 is running,x=%d\n",x);
return NULL;
}
void *thread2(void *arg){
x=x+1;
printf("pthread2 is running,x=%d\n",x);
return NULL;
}
void *thread3 (void *arg){
x=x+1;
printf("pthread3 is running,x=%d\n",x);
return NULL;
}
int main(void){
pthread_t thid1,thid2,thid3;
pthread_create(&thid1,NULL,(void *)thread1,NULL);
sleep(1);
pthread_create(&thid2,NULL,(void *)thread2,NULL);
sleep(1);
pthread_create(&thid3,NULL,(void *)thread3,NULL);
sleep(1);
printf("Main thread exit!\n");
exit(0);
}
5-2编写一个多进程多线程的程序:要求创建4个子进程,每个子进程都分别创建两个线程,进程和线程的功能不作要求,可以只提供简单的打印语句。
【源程序】
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
void *func1()
{
printf("i am a thread,threadId:%u\n",pthread_self());
}
int main(int argc,char *argv[])
{
int pid1,pid2,pid3;
pthread_t tid1,tid2,tid3,tid4,tid5,tid6,tid7,tid8;
pid1 = fork();
switch(pid1)
{
case 0:
pid2 = fork();
switch(pid2)
{
case 0:
printf("i am a process ,pid:%d\n",getpid());
pthread_create(&tid1,NULL,func1,NULL);
pthread_create(&tid2,NULL,func1,NULL);
break;
default:
printf("i am a process ,pid:%d\n",getpid());
pthread_create(&tid3,NULL,func1,NULL);
pthread_create(&tid4,NULL,func1,NULL);
// exit(0);
break;
}
default:
pid3 = fork();
switch(pid3)
{
case 0:
printf("i am a process ,pid:%d\n",getpid());
pthread_create(&tid5,NULL,func1,NULL);
pthread_create(&tid6,NULL,func1,NULL);
break;
default:
printf("i am a process ,pid:%d\n",getpid());
pthread_create(&tid7,NULL,func1,NULL);
pthread_create(&tid8,NULL,func1,NULL);
// exit(0);
break;
}
}
}
5-3 编写一个包含2 个线程的程序,在主线程中创建一个全局变量并初始化为0,在另一个线程对这个全局变量进行递加运算,并在结束时向主线程返回一个结果,由主线程打印输出。
【源程序】
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
long int var = 0;
void *tfn1(void *arg) {
int i = var;
for (int j = 0; j < 3; j++) {
i = i + j;
}
printf("%d\n",i);
pthread_exit(&i);
return NULL;
}
int main(void)
{
pthread_t tid1;
int *ret1;
pthread_create(&tid1, NULL, tfn1, NULL);
pthread_join(tid1, (void **)&ret1);
printf("the result is %ls\n",ret1);
pthread_exit(NULL);
}