python多线程互斥锁问题

之前一直觉得python的多线程有点问题,今天搞了一下多线程的事情;直接上代码了。

#-*- coding:utf8 -*-
#!/usr/bin/env python

import os
import sys
import subprocess
import json
import string
import re
import time
from threading import Thread,Lock

voice_arr = []
g_index = 0
g_len = 0

def load_data(filename):
    global voice_arr
    global g_index
    global g_len
    fp = open(filename, 'rt')
    for line in fp.readlines():
        line = line.strip()
        if len(line) < 1:
            continue
        voice_arr.append(line)
    fp.close()
    g_len = len(voice_arr)
    g_index = 0

def processdata(voice_id):
    voiceId = voice_id
    print(voiceId)
    time.sleep(0.1)
    BASE_URL = "tmp/{voiceId}.wav"
    url = BASE_URL.format(voiceId = voiceId)
    print(url)
    Cmd = 'cp "{url}" data/{voiceId}.wav'
    cmd3 = Cmd.format(url = url, voiceId = voiceId)
    print(cmd3)
    s = subprocess.call(cmd3, shell=True)
    return

def work():
    global voice_arr
    global g_index
    global g_len
    voice_id = ''
    while True:
        voice_id = ''
        lock.acquire()
        if g_index < g_len:
            voice_id = voice_arr[g_index]
            g_index = g_index + 1
            time.sleep(0.05)
        else:
            lock.release()
            break
        lock.release()
        if voice_id != '':
            processdata(voice_id)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('usage: %s input_data' % (sys.argv[0]))
        sys.exit(-1)
    load_data(sys.argv[1])
    lock = Lock()
    thread_num = 50
    thread_arr = []
    for i in range(thread_num):
        p = Thread(target = work)
        thread_arr.append(p)
        p.start()
    for p in thread_arr:
        p.join()

代码中包含系统的调用,整体还是可以的说。
后面关注下,系统调用相关的代码的说。

你可能感兴趣的:(脚本,python基础)