Creation and common methods of Python threads (detailed examples)

David Beckham
Release: 2022-05-16 21:01:15
forward
3428 people have browsed it

This article brings you relevant knowledge aboutpython. It mainly introduces the creation and common methods of threads, as well as some thread demonstration cases. Let’s take a look at them together. I hope Helpful to everyone.

Creation and common methods of Python threads (detailed examples)

Recommended learning:python video tutorial

Creation and use of threads

There are many multi-threading modules in Python, among which thethreading module is more commonly used. Let's take a look at how to usethreading to create threads and its common methods.

Thread creation-threading

##Function name Introduction Example Thread Create thread Thread(target, args) # Introduction to the kinetic energy of ##Thread: Instantiate a thread object by calling the
Thread

class of thethreadingmodule; it has two parameters:target and args(Same parameters as when creating a process).targetis the function to be executed when creating a thread, andargsis the parameters that need to be passed in when executing this function.

Common methods of thread objects

Let’s take a look at the common methods of thread objects:

  • start function: Start a thread; does not have any return value or parameters.
  • join function: the same as the join function in the process; blocking the current program, the main thread's task needs to wait for the current sub-thread's task to end before it can continue to execute; the parameter istimeout: Represents the blocking timeout.
  • getName function: Get the name of the current thread.
  • setName function: set the name for the current thread; the parameter isname: it is a string type
  • is_alive function: determine whether the status of the current thread is in stock
  • setDaemon function: It is a daemon thread; if the script task is completed, it will be forcibly terminated even if the process pool has not completed its business. The same is true for child threads. If you want the main process or the main thread to finish its own business first, and still allow the child threads to continue working instead of forcibly closing them, you only need to setsetDaemon()toTrueThat’s it.

PS: Through the above introduction, you will find that the functions in the thread object are almost very similar to the functions in the process object. Their usage methods and usage scenarios are almost the same.

Thread demonstration case

Single-thread initial case

DemonstrationBefore multi-threadingLet’s take a look at the following case first, and then see how long it took in total after running it

1. Define a list and write some content in it.

2. Define a new list, randomly write the contents of the previous list into the new list; and delete the randomly obtained contents from the previous list.

3. You need to user andombuilt-in module

The code example is as follows:

# coding:utf-8import timeimport random old_lists = ['罗马假日', '怦然心动', '时空恋旅人', '天使爱美丽', '天使之城', '倒霉爱神', '爱乐之城']new_lists = []def work(): if len(old_lists) == 0: # 判断 old_list 的长度,如果为0 ,则表示 该列表的内容已经被删光了 return '\'old_list\' 列表内容已经全部删除' old_choice_data = random.choice(old_lists) # random 模块的 choice函数可以随机获取传入的 old_list 的元素 old_lists.remove(old_choice_data) # 当获取到这个随机元素之后,将该元素从 old_lists 中删除 new_choice_data = '%s_new' % old_choice_data # 将随机获取到的随机元素通过格式化方式重新赋值,区别于之前的元素 new_lists.append(new_choice_data) # 将格式化的新的随机元素添加至 new_lists 列表 time.sleep(1)if __name__ == '__main__': strat_time = time.time() for i in range(len(old_lists)): work() if len(old_lists) ==0: print('\'old_lists\' 当前为:{}'.format(None)) else: print(('\'old_lists\' 当前为:{}'.format(old_lists))) if not len(new_lists) == 0: print(('\'new_lists\' 当前为:{}'.format(new_lists))) else: print('\'new_lists\' 当前为:{}'.format(None)) end_time = time.time() print('运行结束,累计耗时:{} 秒'.format(end_time - strat_time))
Copy after login

The running result is as follows:


Creation and common methods of Python threads (detailed examples)

From the running output results, we can see that the entire script takes 7 seconds to run, andnew_listsThe elements in the list have been formatted and added_new; Not only that, because of therandom module's choice function, the content order ofnew_listsis also different fromold_lists; each The running order will be different every time, so the order ofold_listscannot be guaranteed.


Multi-threaded demonstration case

The code example is as follows:

# coding:utf-8import timeimport randomimport threading old_lists = ['罗马假日', '怦然心动', '时空恋旅人', '天使爱美丽', '天使之城', '倒霉爱神', '爱乐之城']new_lists = []def work(): if len(old_lists) == 0: # 判断 old_list 的长度,如果为0 ,则表示 该列表的内容已经被删光了 return '\'old_list\' 列表内容已经全部删除' old_choice_data = random.choice(old_lists) # random 模块的 choice函数可以随机获取传入的 old_list 的元素 old_lists.remove(old_choice_data) # 当获取到这个随机元素之后,将该元素从 old_lists 中删除 new_choice_data = '%s_new' % old_choice_data # 将随机获取到的随机元素通过格式化方式重新赋值,区别于之前的元素 new_lists.append(new_choice_data) # 将格式化的新的随机元素添加至 new_lists 列表 time.sleep(1)if __name__ == '__main__': strat_time = time.time() print('\'old_lists\'初始长度为:{}'.format(len(old_lists))) # 获取 old_lists 与 new_lists 最初始的长度 print('\'new_lists\'初始长度为:{}'.format(len(new_lists))) thread_list = [] # 定义一个空的 thread_list 对象,用以下方添加每个线程 for i in range(len(old_lists)): thread_work = threading.Thread(target=work) # 定义一个线程实例化对象执行 work 函数,因为 work 函数没有参数所以不用传 args thread_list.append(thread_work) # 将 thread_work 添加进 thread_list thread_work.start() # 启动每一个线程 for t in thread_list: # 通过for循环将每一个线程进行阻塞 t.join() if len(old_lists) ==0: print('\'old_lists\' 当前为:{}'.format(None), '当前长度为:{}'.format(len(old_lists))) else: print(('\'old_lists\' 当前为:{}'.format(old_lists))) if not len(new_lists) == 0: print('\'new_lists\' 当前长度为:{}'.format(len(new_lists))) print('\'new_lists\' 当前的值为:{}'.format(new_lists)) else: print('\'new_lists\' 当前为:{}'.format(None)) end_time = time.time() print('运行结束,累计耗时:{} 秒'.format(end_time - strat_time))
Copy after login

The running results are as follows:


Creation and common methods of Python threads (detailed examples)

Judging from the running results, our initial single-threaded task took 7 seconds. After using multi-threading, it only took 1 second to complete, which greatly improved our operating efficiency.


Thread issues

Through the above exercises, we found that the use of threads is almost exactly the same as that of processes. They can all execute programs without interfering with each other, and can also prevent the main thread's program from waiting for the sub-thread's task to be completed before executing it. It’s just that in the demonstration case just now, we used thejoin()function to block. You can removejoin()here to see the execution effect.

Like processes, threads also have certain problems.

  • The function executed by the thread also cannot obtain the return value.
  • When multiple threads modify a file at the same time, it will also cause the data of the modified file to be confused (because they all operate a file concurrently, especially when dealing with transaction scenarios, you need to pay special attention).

The problems existing in these threads can also be solved. We will introduce them in detail in the next chapterThread Pool and Global Lock.

Recommended learning:python video tutorial

Function name ##start Start the thread start() join Block the thread until the thread execution ends join(timeout=None) getName Get the name of the thread getName() setName Set The name of the thread setName(name) is_alive Determine whether the thread is alive is_alive() setDaemon Daemon thread setDaemon(True)
Introduction Usage

The above is the detailed content of Creation and common methods of Python threads (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!