thread Modules in python3 Change to _thread, All kinds of posts on the Internet say that novices are not recommended to use thread, You have to taste it or not .

 import _thread
def print_num():
for i in range(100):
print(i) _thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())
_thread.start_new_thread(print_num,())

Guess what the run result is ?

Nothing happened ...... Because the main thread doesn't do anything and ends up . When the main thread exits, the child thread hangs before it can run ,

That is to say, the mainline will not wait for the child thread to finish executing before exiting .

Now the thread lock comes out .

_thread.allocate_lock() Generate a lock , Lock at the beginning of the thread function , Unlock at the end , The main line decides whether to exit by judging the state of the lock .

 import _thread
def print_num(lock): # Thread functions
for i in range(100):
print(i)
lock.release() # Generate 5 The lock
locks = []
for i in range(5):
lock = _thread.allocate_lock()
lock.acquire()
locks.append(lock)
# start-up 5 Threads , A lock for each
for i in range(len(locks)):
_thread.start_new_thread(print_num,(locks[i],)) # The main thread monitors the state of each lock separately , Knowing that all locks are not locked , sign out
for i in range(len(locks)):
while locks[i].locked():
pass

python thread More articles on Multithreading

  1. Python The multithreading (threading) With multiple processes (multiprocessing )

    process : An execution of a program ( The program loads into memory , The system allocates resources to run ). Each process has its own memory space , Data stack, etc , Processes can communicate with each other , But you can't share information . Threads : All threads run in the same process , Share the same running environment . Each individual ...

  2. Python GIL Multithreading mechanism (C source code)

    Recent reading <Python Source analysis > Encapsulation of process threads : GIL,Global Interpreter Lock, about python Multithreading is very important , How to achieve it ? The code is implemented as follows : Point to one ...

  3. Python Implement multithreading HTTP Downloader

    This article introduces the use of Python Write multithreading HTTP Downloader , And generate .exe Executable file . Environmental Science :windows/Linux + Python2.7.x Single thread Before we talk about multithreading, let's talk about single threading . The idea of writing a single thread is ...

  4. Python thread local

    because GIL Why , I hardly use it in daily development python The multithreading . If concurrency is needed , Multi process is generally used , about IO Bound This situation , It's also a good idea to use coroutine . But in python A lot of Network Libraries , Both support multithreading , ...

  5. How to achieve Python Universal multithreading / Process parallel module

    When single thread performance is insufficient , We usually use multithreading / Multiple processes to speed up running . And the amount of code is often hopeless , You need to consider : How to create functions executed by threads ? How to collect results ? If you want the result to return from the child thread to the main thread , The queue is also used How to cancel execution ? ...

  6. Python: Multithreaded programming

    1.IO Programming IO(input/output). Where data exchange is used , It's all about io Programming , For example, disk , Network data transmission . stay IO Programming ,stream( flow ) It's an important concept , Divided into input streams (input strea ...

  7. Python Implementation of multi-threaded calls GDAL Perform orthorectification

    python Implementation of multithreading reference http://www.runoob.com/python/python-multithreading.html #!/usr/bin/env python # coding: ...

  8. Python Multithreading and multiprocessing

    One . Multithreading 1. Sequential execution of a single thread , Pay attention to the sequence of execution , Need to use join. #coding=utf-8 from threading import Thread import time def my_co ...

  9. 【python】 Multi thread explanation

    One . Process thread relationship A process contains at least one thread . Two . Thread basis 1. State of thread Threads have 5 States , The process of state transition is shown in the figure below : 2. Thread synchronization ( lock ) The advantage of multithreading is that it can run multiple tasks at the same time ( At least it feels like this ) ...

Random recommendation

  1. PAT 1047. Programming team competition (20)

    The rules of the programming team competition are : Each team consists of several players : All the players play on their own : The result of the team is the result of all the players and : The team with the highest score wins . Now all players are given the results of the game , Please write a program to find the champion team . Input format : Enter the first line to give a positive value ...

  2. linux- Common commands for chatting in the form of commands

    When we're in Linux Use the command under the terminal “who” or “w” when , We always see a long list of users , here , Do you really want to send him a message / she . If she's the one you've been looking for for a long time MM, And you happen to see her there as well , Forced by shy you , Right now ...

  3. solve vista and win7 stay windows Interactive desktop permissions in services : through Session 0 Isolation

        In a large foreign automobile company BI In the project , There is a subproject , You need to display the sales report on the big screen , The program needs to start and close automatically . Developers in the development process , Found in Win7 Of service It can't be operated directly in UI process , In the course of the investigation , Discovery is like ...

  4. C Language tools ---Code::Blocks

    Code::Blocks Code::Blocks It's an open source, full-featured, cross platform C/C++ Integrated development environment . Code::Blocks It's open source software . By pure C++ Language development completed , It uses the famous GUI Library wx ...

  5. hdu 2952 Counting Sheep

    This question comes from :http://acm.hdu.edu.cn/showproblem.php?pid=2952 The question : The up and down or so 4 Two directions for a group of . Search for a few flocks of sheep #include <stdio.h> # ...

  6. java The method of sending mail with pictures is realized

    package sendEmail; import java.util.Properties; import javax.activation.DataHandler; import javax.ac ...

  7. geek Web Front end development resources

    Front end development has become one of the hottest technologies . This week we will bring you technical information , Other sites that technicians often use . I hope you don't miss our content this week . From the original : Geek tag It's very difficult to knock code for Shenma Program the ape do ...

  8. front end MVC Vue2 Learning summary ( 3、 ... and )—— Template syntax 、 filter 、 Compute properties 、 The observer 、Class And Style binding

    Vue.js Based on HTML The template syntax of , Allow developers to declaratively put DOM Bind to the bottom Vue Instance data . all Vue.js The templates are all legal HTML , So browsers and HTML Explain ...

  9. Jenkins Continuous integration practice java Project automation deployment

    About Linux install Jenkins Check out this blog post Ubuntu16.04 Environmental installation jenkins 1. Install the deployment plug-in Enter plug-in management , And search for the plug-in Deploy to container Plugin Carry on safety ...

  10. redis Study ( 6、 ... and )——Sorted Set data type

    One . summary : Sorted Set( Ordered set ) and Set The type is very similar , They are all sets of strings , Do not allow duplicate members to appear in a Set in . The main difference between them is Sorted Set Each member in will have a score (sc ...