GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — LearnPythonStats/net_thread_queue.py at master · elthe/LearnPythonStats

Expand file tree

/

net_thread_queue.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
69 lines (56 loc) · 1.79 KB
/

net_thread_queue.py

Copy path

File metadata and controls

69 lines (56 loc) · 1.79 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
多线程,线程锁,任务队列的简单例子
"""
import queue
import time
import threading
import numpy as np
from common import logcm
from common import datecm
def run_task(sleep_seconds):
# 声明使用全局锁
global lock, queue_list
# 取得当前线程
thd_now = threading.current_thread()
thd_name = thd_now.getName()
# 循环直到任务队列为空
while not queue_list.empty():
# 取得任务编号
task = queue_list.get()
# 锁请求
if lock.acquire():
# 当前时间
now_time = datecm.now_time_str('%Y-%m-%d %H:%M:%S')
# 输出日志(同时只有一个线程可以写日志)
logcm.print_info("%s is doing %s sleep %d seconds. %s " % (thd_name, task, sleep_seconds, now_time))
# 释放锁
lock.release()
# 等待N秒后继续
time.sleep(sleep_seconds)
# 初始化任务队列
queue_list = queue.Queue()
for i in range(10):
# 在队列中加入新的任务号
queue_list.put('Task-%d' % (i + 1))
# 线程锁
lock = threading.Lock()
# 启动多个线程
thd_list = []
for i in range(5):
# 新建线程,指定执行方法及参数
rands = np.random.randint(1, 4)
thd = threading.Thread(target=run_task, args=(rands,))
thd_list.append(thd)
# 设定线程的名称
thd.setName("Thread-%d" % (i + 1))
# 启动线程
thd.start()
# 调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。
# 参数timeout是一个数值类型,表示超时时间,
# 如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。
# for thd in thd_list:
# thd.join()
# 所有线程结束后,自动退出程序
# sys.exit()
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.