Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何判断所有线程任务是否已经完成? #1

Open
zenwan opened this issue Dec 10, 2018 · 2 comments
Open

如何判断所有线程任务是否已经完成? #1

zenwan opened this issue Dec 10, 2018 · 2 comments

Comments

@zenwan
Copy link

zenwan commented Dec 10, 2018

import vthread
import time

alist=[]
@vthread.pool(3,join=False)
def some(a, b, c):
    time.sleep(1)
    s = a + b + c
    alist.append(s)

def foo():
    for i in range(10):
         some(i, i, i)
print(alist)

什么时候获取alist?

@cilame
Copy link
Owner

cilame commented Dec 10, 2018

import vthread
import time

alist=[]
@vthread.pool(3,join=False)
def some(a, b, c):
    time.sleep(1)
    s = a + b + c
    alist.append(s)

def foo():
    for i in range(10):
         some(i, i, i)

foo() # 你的代码少了函数执行
time.sleep(4) # 如果不考虑其他,光凭意念的话,你完全可以用sleep来等函数执行完
print(alist)

关于多线程,任务的结果一般是用管道来实现会更好一点。
下面的代码,这样或许会更安全。

import vthread
import time
import queue

ls = [1,44,32,45,67,88,99,100,55]

q = queue.Queue()

@vthread.pool(3)
def func(i):
    try:
        r = i + i + i
        time.sleep(1)
        if r == 3:
            raise
    except:
        r = None # 按照数量的put和get需要注意异常的消费
    print(r) # log
    q.put(r)
        

for i in ls:
    func(i)

alist = [q.get() for i in range(len(ls))]
print(alist)

@SunYong0821
Copy link

import vthread
import time

alist=[]
@vthread.pool(3,join=False)
def some(a, b, c):
    time.sleep(1)
    s = a + b + c
    alist.append(s)

def foo():
    for i in range(10):
         some(i, i, i)

foo() # 你的代码少了函数执行
time.sleep(4) # 如果不考虑其他,光凭意念的话,你完全可以用sleep来等函数执行完
print(alist)

关于多线程,任务的结果一般是用管道来实现会更好一点。
下面的代码,这样或许会更安全。

import vthread
import time
import queue

ls = [1,44,32,45,67,88,99,100,55]

q = queue.Queue()

@vthread.pool(3)
def func(i):
    try:
        r = i + i + i
        time.sleep(1)
        if r == 3:
            raise
    except:
        r = None # 按照数量的put和get需要注意异常的消费
    print(r) # log
    q.put(r)
        

for i in ls:
    func(i)

alist = [q.get() for i in range(len(ls))]
print(alist)

为什么不提供返回值?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants