进程与线程-操作系统

敬请T期待 Lv3

进程

实验说明

Ø进程是资源分配单位,fork产生的进程只是对父进程所有资源的克隆;

Ø引入线程后,线程是运行单位,但仍共享父进程的资源。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//procssees.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
pid_t son_pid,daughter_pid;
int count =1;
son_pid =fork();
if (son_pid == 0){
count ++;
printf("i am son, count =%d\n",count);
}else{
daughter_pid = fork();
if(daughter_pid == 0 ){
count ++;
printf("i am daughter,count=%d\n",count);
}
else{
count ++;
printf("i am father,count=%d\n",count);
waitpid(son_pid,NULL,0);
waitpid(daughter_pid,NULL,0);
}
}
}

运行结果:

进程

为什么出现son、daughter、father三个进程顺序不一致情况?

当使用如fork()这样的系统调用来创建进程时,新创建的进程(子进程)与父进程是并发执行的。这意味着操作系统可以自由地调度这些进程,使它们以任何顺序运行。每个进程都有自己的执行路径和生命周期,它们可能会因为等待I/O操作、系统资源限制、其他进程的优先级等原因而被挂起或延迟执行。因此,在并发编程中,进程的执行顺序通常是不确定的。

为什么每个进程的count变量都是2?

当使用fork()创建新进程时,父进程的内存空间(包括全局变量和静态变量)会被复制到子进程中。这意味着子进程将拥有与父进程相同的变量副本,但这些副本是独立的,对其中一个进程的变量进行修改不会影响其他进程的变量(除非使用了某种形式的进程间通信或共享内存)。

线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//thread.c
#include <unistd.h>
#include<stdio.h>
#include<pthread.h>
void *daugther(void *num){
int* a =(int *)num;
*a += 1;
printf("I am a daughter,count=%d\n",*a);
}
void *son(void *num){
int *a = (int *)num;
*a += 1;
printf("I am son,count=%d\n",*a);
}
int main(){
pthread_t son_tid,daugther_tid;
int count = 1;

pthread_create(&son_tid,NULL,son,&count);
pthread_create(&daugther_tid,NULL,daugther,&count);

count++;
printf("I am parent,count:=%d\n",count);
pthread_join(son_tid,NULL);
pthread_join(daugther_tid,NULL);

return 0;
}

代码结果:

线程

count变量为什么不一样?

在多线程编程中,如果多个线程同时访问和修改同一个共享变量(如count),而没有适当的同步机制来保护这个变量,那么就会出现竞态条件(race condition)。竞态条件会导致变量的值变得不可预测,因为不同的线程可能会在没有任何顺序保证的情况下交替地读取和写入这个变量。son线程和daugther线程都试图修改共享的count变量。同时,主线程也在修改这个变量。由于这三个线程之间没有使用锁、互斥量或其他同步机制来确保对count变量的访问是原子的,因此count变量的值可能会在多个线程之间变得不一致。

  • Title: 进程与线程-操作系统
  • Author: 敬请T期待
  • Created at : 2024-10-26 19:13:20
  • Updated at : 2024-10-31 22:01:47
  • Link: https://kingwempity.github.io/2024/10/26/进程与线程-操作系统/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
进程与线程-操作系统