Threaded operation 118 python program - to create multi-threaded

A, python threading module

1.1 thread and threading modules

  • thread module provides support for basic threads and locks
  • threading provides a higher level, more powerful thread management functions.

1.2 Queue module

  • Queue module allows users to create a queue data structure may be used for sharing data among multiple threads.

1.3 attention to the selection module

  1. Avoid using the thread module
  2. Because higher-level threading module more advanced, more complete support for threads
  3. And the use of thread module inside the property there is a conflict may occur with threading;
  4. Second, synchronization primitives low-level thread module rarely (actually only one), but there are a lot of threading module;
  5. Furthermore, thread module When the main thread, all threads will be forced to end off, without warning there will not be a normal cleanup, at least threading module can ensure that important sub-thread exits before the exit process.

Note: the Thread module does not support daemon thread, when the main thread exits, all of the child threads regardless of whether they are still working, will be forced out. The threading module supports daemon thread, usually a daemon thread waits for the server requests the client, if the client did not request it in waiting for that, if set to a thread as a daemon thread, it means that the thread is not important in the process when exiting, without waiting for the thread to exit.

Two, Threading module

multiprocess module completely mimics the threading module interfaces, both at the level of use, there are a lot of similarities, and thus will not be described in detail (official link)

Third, to create a thread class by Threading.Thread

3.1 way to create a thread

1.直接通过Threading.Thread来创建
from threading import Thread
import time

def task(name):
    print(f'子线程{name} is running')
    time.sleep(1)
    print(f'子线程{name} is end')
    
# 因为创建线程不需要重新开辟内存空间,所以不用写main,创建线程只是单独把启动线程函数里面的代码拿出来用
t = Thread(target=task,args=('Cecilia陈',))
t.start()
print('主线程结束')

Cecilia Chen child thread is running

The main thread ends

Cecilia is end child thread

3.2 Second way to create a thread

2.通过自定义类来继承Thread类来创建线程
from threading import Thread
import time

class MyDic(Thread,name):
    def __init__(self,name)
        super().__init__()
        self.name = name
    
    def run(self):
        print(f'子线程{name} is running')
        time.sleep(1)
        print(f'子线程{name} is end')

       
t = Mydic('Cecilia陈')
t.start()
print('主进程结束')
    

Cecilia Chen threads start
the main process
thread Cecilia Chan end

Fourth, multi-threaded and multi-process comparison

Comparison of 4.1 pid

from threading import Thread
from multiprocessing import  Process
import time
import os

def task(name):
    print(f'子线程{name} is running')
    time.sleep(1)
    print(f'子线程{name} is end')
    print(f'子线程{name}的pid:{os.getpid()}')


def task1(name):
    print(f'进程{name} is running')
    time.sleep(1)
    print(f'进程{name} is end')
    print(f'进程的{name}pid:{os.getpid()}')


if __name__ == '__main__':
    # part1:在主进程下开启多个线程,每个线程都跟主进程的pid一样
    t = Thread(target=task, args=('Cecilia陈',))
    t.start()
    t.join()
    print(f'主线程的pid:{os.getpid()}')

    
    # 开多个进程,每一个进程的pid号都不一样
    p = Process(target=task1,args=('xichen',))
    p1 = Process(target=task1,args=('xixi',))
    p.start()
    p1.start()
    p.join()
    p1.join()
    print(f'主进程的pid:{os.getpid()}')

Child thread Cecilia Chan is running
sub-thread Cecilia Chen is end
child thread Cecilia Chen pid: 10892
main thread pid: 10892
process xixi is running
the process xichen is running
the process xichen is end
process xixi is end
xichenpid process: 6844
xixipid process : 13700
pid main processes: 10892

4.2 thread and process efficiency contest open

from threading import Thread
from multiprocessing import Process
import time

def task(name):
    print(f'{name} is running')
    time.sleep(2)
    print(f'{name} is end')


if __name__ == '__main__':
    t = Thread(target=task,args=('子线程',))
    p = Process(target=task,args=('子进程',))
    t.start()
    # p.start()
    print('主')

1. Turn the thread speed:

Child thread is running

the Lord

Child thread is end

2. Turn on the speed of the process:

the Lord

Child process is running

Child process is end

4.3 Memory data sharing

from threading  import Thread
from multiprocessing import  Process
import time,os

x = 100
def task():
    global x
    x = 50 # 此时线程是在拿全局的x的值
    print(os.getpid()) # 因为开启线程是不需要操作系统给线程分配内存空间的,所以线程用的是它当前所在的进程的进程号


if __name__ == '__main__':
    # 线程
    t = Thread(target=task)
    t.start()
    time.sleep(2)
    print(x) # 50,这里说明线程他是共享他所在进程下的所有资源,对资源进行一系列的操作
    print(os.getpid())

    # 进程
   # p = Process(target=task)
   # p.start() 
   # print(x) # 这里的x还是主进程的x 100

Five, Thread of other methods

Thread instance object:

  • isAlive(): Returns the thread is active.
  • getName(): Returns the thread name.
  • setName(): Set the thread name.

Some methods provided by threading module:

  • threading.currentThread(): Returns the current thread variable.
  • threading.enumerate(): Returns a list containing the running thread. Refers to the thread starts running, before the end, it does not include a thread before starting and after termination.
  • threading.activeCount(): Returns the number of running threads, and len (threading.enumerate ()) have the same result.

Code Example 5.1

from threading import Thread,currentThread,enumerate,activeCount
import time

def task():
    print('子线程 start')
    time.sleep(2)
    print('子线程 end')
    print(enumerate())# 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
    print(currentThread(),'子线程') # 返回当前的线程变量
    print(activeCount())

if __name__ == '__main__':
   t1 = Thread(target=task)
   t2 = Thread(target=task)
   t1.start()
   t2.start()
   t2.setName('Cecilia陈')
   print(t2.getName()) # 得到t2的线程名字,是我们设置好的Cecilia陈
   print(t1.getName()) # 得到t1的线程名子 Thread-1
   print(t1.is_alive()) # True

5.2 join method

from threading import Thread
import time
def task():
    print('子线程 start')
    time.sleep(2)
    print('子线程 end')

t = Thread(target=task)
t.start()
t.join() # 等待子线程运行结束
print('主线程')

Sixth, multithreading socket

6.1 server

import socket
from threading import Thread

socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.bind(('192.168.11.78',8004))
socket.listen(5)

def action(conn,addr):
    while True:
        try:

            msg = (conn.recv(1024)).decode('utf8').upper()
            print(f'客户端{addr}发送的数据为:{msg.lower()}')
            print(f'向客户端{addr}发送数据为',msg)
            conn.send(msg.encode('utf8'))
        except:
            break


if __name__ == '__main__':
    print('等待客户端连接:')
    while True:
        try:
            conn,addr = socket.accept()
            print(f'客户端已连接{addr}')
            t = Thread(target=action,args=(conn,addr))
            t.start()
        except:
            print(f'客户端{addr}断开连接 !!')
            break

6.2 Client

import  socket

client = socket.socket()
client.connect(('192.168.11.78',8004))

while True:
    msg = input('输入:')
    if msg == 'q':
        break
    client.send(msg.encode('utf8'))
    flag = client.recv(1024)
    print('接收服务端的数据为:',flag.decode('utf8'))

Guess you like

Origin www.cnblogs.com/xichenHome/p/11569078.html