线程

import time
from threading import Thread

def func(n):
    time.sleep(1)
    print(n)
for i in range(10):
    t = Thread(target=func,args=(i,))
    t.start()
from threading import Thread
import time

class MyThread(Thread):
    def __init__(self,arg):
        super().__init__()
        self.arg = arg

    def run(self):
        time.sleep(1)
        print(self.arg)
t = MyThread(10)
t.start()

 

from threading import Thread
import time,os
#多线程并发
def func(n):
    time.sleep(1)
    print(n,os.getpid())

print('主线程:',os.getpid())
for i in range(10):
    t = Thread(target=func,args=(i,))
    t.start()

 

from threading import Thread
from multiprocessing import Process
import time

def func(n):
    n + 1

if __name__ == '__main__':
    st = time.time()
    t_lst = []
    for i in range(100):
        t = Thread(target=func,args=(i,))
        t.start()
        t_lst.append(t)
    for t in t_lst: t.join()
    t1 = time.time() - st

    st2 = time.time()
    t_lst2 = []
    for i in range(100):
        t = Process(target=func,args=(i,))
        t.start()
        t_lst2.append(t)
    for t in t_lst2: t.join()
    t2 = time.time() - st2
    print(t1,t2)

 

from threading import Thread

def demo(n):
    inp = input('%s:'%n)
    print(inp)

for i in range(5):
    t = Thread(target=demo,args=('name%d'%i,))
    t.start()

 

import threading,time

def func(n):
    time.sleep(0.5)
    print(n,threading.current_thread(),threading.get_ident())

for i in range(10):
    threading.Thread(target=func,args=(i,)).start()

print(threading.activeCount())
print(threading.current_thread())
print(threading.enumerate())

 

转载于:https://www.cnblogs.com/kuraki/p/9614813.html

你可能感兴趣的:(线程)