python core --- multitasking (Linux)

Multitasking (under Linux)

1. Process creation
os.fork() creates a process

import os
ret = os.fork() # 创建一个新的进程
print("haha")
结果为
haha
haha

import os
import time
ret = os.fork() # 创建一个返回值等于0的子进程,而父进程是一个大于0的值
if ret == 0:
    while True:
        print("---1---")
        time.sleep(1)
else:
    while True:
        print("---2---")
        time.sleep(1)
结果为:
---1---
---2---
---1---
---2---
---1---
---2---
---1---
---2---
....

os.getpid() # Get the id of the child process created by the parent process
os.getppid() # Get the id of the parent process

import os
ret = os.fork()
print(0)
if ret > 0:
    print("---父进程---%d" %os.getpid())
else:
    print("---子进程---%d--%d" %(os.getpid(), os.getppid()))
结果为
20570
---父进程---20569
0
---子进程---20570--20569


The return value of fork in the parent
process is the id of the child process just created

import os
import time

ret = os.fork()

if ret == 0:
    print("---子进程---")
    time.sleep(5)
    print(---子进程over---)
else:
    print("---父进程---")
    time.sleep(3)
print("over")
结果为
---父进程---
over
---子进程---

---子进程over---
over

3. In multiple processes, data is not shared

import os
import time

g_num = 100
ret = os.fork()

if ret == 0:
    print("---process1---")
    g_num +=1
    print("---process1---%d" %g_num)
else:
    time.slepp(3)
    print("---process---")
    print("---process2---%d" %g_num)
结果为
---process1---
---process1---101
---process2---
---process2---100

4. Multiple forks
see the code below

import os
import time

ret = os.fork()  # 创建了一个进程,现在有两个进程
if ret == 0:
    print("---1---")
else:
    print('---2---')
ret = os.fork()  # 两个进程分别创建了一个进程,现在有四个进程
if ret == 0:
    print('---11---')
else:
    print('---22---')

结果为:
---2---
---22---
---11---
---1---
---22---
---11---

Look at the following code

import os
import time

ret = os.fork()  # 创建了一个进程,现在有两个进程
if ret == 0:
    print("---1---")
else:
    print('---2---')
    ret = os.fork()  # 一个进程创建了一个进程,现在有三个进程
    if ret == 0:
        print('---11---')
    else:
        print('---22---')

结果为:
---2---
---22---
---1---
---11---

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324818145&siteId=291194637