簡體   English   中英

Python3-每個線程在函數中使用n +1個值

[英]Python3 - Each thread to use n + 1 value within function

我正在編寫一個腳本,以發送帶有從JSON文件加載的一些數據的發布請求。

JSON:

[
  {
    "title": "Mr",
    "firstname": "Joe",
    "lastname": "Blogs",
    "phonenumber": 7901893333
  },
  {
    "title": "Miss",
    "firstname": "Jane",
    "lastname": "Wang",
    "phonenumber": 7901894444
  },
  {
    "title": "Mrs",
    "firstname": "Rosie",
    "lastname": "Thomas",
    "phonenumber": 7901895555
  }
]

碼:

import requests
import json
import threading

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

def send_info():
    url = 'http://ptsv2.com/t/e092q-1537974317/post'

    payload = {
    'titleCode': data[0]["title"],
    'firstName': data[0]["firstname"],
    'lastName': data[0]["lastname"],
    'cellPhone': data[0]["phonenumber"] 
    }

    r = requests.post(url, params=payload)

    print(r.text)

threads = []
for i in range(len(data)):
    t = threading.Thread(target=send_info)
    threads.append(t)
    t.start()

目前,所有線程都僅使用“ data [0]”。

如何讓一個線程使用“ data [0]”,下一個線程使用“ data [1]”,下一個線程使用“ data [2]”?

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    p = Pool(5)
    print(p.map(f, [1, 2, 3]))

其中[1、2、3]是將用作f()方法輸入的參數數組。

來源: https : //docs.python.org/2/library/multiprocessing.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM