程序簡單了解和使用

2022-08-01 18:06:16 字數 3338 閱讀 3530

1

. 程序

-程序間資料不共享

data_list =

def task(arg):

print(data_list)

def run():

for i in range(10

): p = multiprocessing.process(target=task,args=(i,))

# p = threading.thread(target=task,args=(i,))

p.start()

if __name__ == '

__main__':

run()

-常用功能:

-join

-deamon

-name

-multiprocessing.current_process()

- multiprocessing.current_process().ident/pid

-類繼承方式建立程序

class

myprocess(multiprocessing.process):

def run(self):

print(

'當前程序

',multiprocessing.current_process())

def run():

p1 =myprocess()

p1.start()

p2 =myprocess()

p2.start()

if __name__ == '

__main__':

run()

2. 程序間資料共享

queue:

linux:

q =multiprocessing.queue()

def task(arg,q):

q.put(arg)

def run():

for i in range(10

): p = multiprocessing.process(target=task, args=(i, q,))

p.start()

while

true:

v = q.get

() print(v)

run()

windows:

def task(arg,q):

q.put(arg)

if __name__ == '

__main__':

q =multiprocessing.queue()

for i in range(10

): p = multiprocessing.process(target=task,args=(i,q,))

p.start()

while

true:

v = q.get

() print(v)

manager:(*)

linux:

m =multiprocessing.manager()

dic =m.dict()

def task(arg):

dic[arg] = 100

def run():

for i in range(10

): p = multiprocessing.process(target=task, args=(i,))

p.start()

input(

'>>>')

print(dic.values())

if __name__ == '

__main__':

run()

windows:

def task(arg,dic):

time.sleep(2)

dic[arg] = 100

if __name__ == '

__main__':

m =multiprocessing.manager()

dic =m.dict()

process_list =

for i in range(10

): p = multiprocessing.process(target=task, args=(i,dic,))

p.start()

while

true:

count = 0

for p in

process_list:

ifnot p.is_alive():

count += 1

if count ==len(process_list):

break

print(dic)

3. 程序鎖

import time

import threading

import multiprocessing

lock =multiprocessing.rlock()

def task(arg):

print(

'鬼子來了')

lock

.acquire()

time.sleep(2)

print(arg)

lock

.release()

if __name__ == '

__main__':

p1 = multiprocessing.process(target=task,args=(1

,)) p1.start()

p2 = multiprocessing.process(target=task, args=(2

,)) p2.start()

為什麼要加鎖?

4. 程序池

import time

from

concurrent.futures import threadpoolexecutor,processpoolexecutor

def task(arg):

time.sleep(2)

print(arg)

if __name__ == '

__main__':

pool = processpoolexecutor(5

)

for i in range(10

): pool.submit(task,i)

Linux 程序簡單了解

首先我們先了解下程式和程序的區別 程式是儲存在硬碟 光碟等介質中的可執行 和資料,是硬碟 外設 上的乙個普通檔案。程序是在cpu及記憶體中執行的程式 就是被載入到記憶體裡的程式 程序大體要了解如下內容 描述程序 pcb linux下的pcb是 task struct task struct內容分類 ...

簡單了解程序間通訊

from multiprocessing import process,queue import os,time def write q print 啟動寫子程序 s os.getpid for chr in a b c d q.put chr time.sleep 1 print 結束寫子程序 s...

python 程序鎖和程序池簡單使用

程序鎖 from multiprocessing import process,lock 程序鎖def f l,i l.acquire print hello world i l.release if name main lock lock for num in range 10 process t...