figure:last-child { margin-bottom: 0.5rem; }
#write ol, #write ul { position: relative; }
img { max-width: 100%; vertical-align: middle; }
button, input, select, textarea { color: inherit; font: inherit; }
input[type="checkbox"], input[type="radio"] { line-height: normal; padding: 0px; }
*, ::after, ::before { box-sizing: border-box; }
#write h1, #write h2, #write h3, #write h4, #write h5, #write h6, #write p, #write pre { width: inherit; }
#write h1, #write h2, #write h3, #write h4, #write h5, #write h6, #write p { position: relative; }
p { line-height: inherit; }
h1, h2, h3, h4, h5, h6 { break-after: avoid-page; break-inside: avoid; orphans: 2; }
p { orphans: 4; }
h1 { font-size: 2rem; }
h2 { font-size: 1.8rem; }
h3 { font-size: 1.6rem; }
h4 { font-size: 1.4rem; }
h5 { font-size: 1.2rem; }
h6 { font-size: 1rem; }
.md-math-block, .md-rawblock, h1, h2, h3, h4, h5, h6, p { margin-top: 1rem; margin-bottom: 1rem; }
.hidden { display: none; }
.md-blockmeta { color: rgb(204, 204, 204); font-weight: 700; font-style: italic; }
a { cursor: pointer; }
sup.md-footnote { padding: 2px 4px; background-color: rgba(238, 238, 238, 0.7); color: rgb(85, 85, 85); border-radius: 4px; cursor: pointer; }
sup.md-footnote a, sup.md-footnote a:hover { color: inherit; text-transform: inherit; text-decoration: inherit; }
#write input[type="checkbox"] { cursor: pointer; width: inherit; height: inherit; }
figure { overflow-x: auto; margin: 1.2em 0px; max-width: calc(100% + 16px); padding: 0px; }
figure > table { margin: 0px !important; }
tr { break-inside: avoid; break-after: auto; }
thead { display: table-header-group; }
table { border-collapse: collapse; border-spacing: 0px; width: 100%; overflow: auto; break-inside: auto; text-align: left; }
table.md-table td { min-width: 32px; }
.CodeMirror-gutters { border-right: 0px; background-color: inherit; }
.CodeMirror-linenumber { user-select: none; }
.CodeMirror { text-align: left; }
.CodeMirror-placeholder { opacity: 0.3; }
.CodeMirror pre { padding: 0px 4px; }
.CodeMirror-lines { padding: 0px; }
div.hr:focus { cursor: none; }
#write pre { white-space: pre-wrap; }
#write.fences-no-line-wrapping pre { white-space: pre; }
#write pre.ty-contain-cm { white-space: normal; }
.CodeMirror-gutters { margin-right: 4px; }
.md-fences { font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; overflow: visible; white-space: pre; background: inherit; position: relative !important; }
.md-diagram-panel { width: 100%; margin-top: 10px; text-align: center; padding-top: 0px; padding-bottom: 8px; overflow-x: auto; }
#write .md-fences.mock-cm { white-space: pre-wrap; }
.md-fences.md-fences-with-lineno { padding-left: 0px; }
#write.fences-no-line-wrapping .md-fences.mock-cm { white-space: pre; overflow-x: auto; }
.md-fences.mock-cm.md-fences-with-lineno { padding-left: 8px; }
.CodeMirror-line, twitterwidget { break-inside: avoid; }
.footnotes { opacity: 0.8; font-size: 0.9rem; margin-top: 1em; margin-bottom: 1em; }
.footnotes + .footnotes { margin-top: 0px; }
.md-reset { margin: 0px; padding: 0px; border: 0px; outline: 0px; vertical-align: top; background: 0px 0px; text-decoration: none; text-shadow: none; float: none; position: static; width: auto; height: auto; white-space: nowrap; cursor: inherit; -webkit-tap-highlight-color: transparent; line-height: normal; font-weight: 400; text-align: left; box-sizing: content-box; direction: ltr; }
li div { padding-top: 0px; }
blockquote { margin: 1rem 0px; }
li .mathjax-block, li p { margin: 0.5rem 0px; }
li { margin: 0px; position: relative; }
blockquote > :last-child { margin-bottom: 0px; }
blockquote > :first-child, li > :first-child { margin-top: 0px; }
.footnotes-area { color: rgb(136, 136, 136); margin-top: 0.714rem; padding-bottom: 0.143rem; white-space: normal; }
#write .footnote-line { white-space: pre-wrap; }
@media print {
body, html { border: 1px solid transparent; height: 99%; break-after: avoid; break-before: avoid; }
#write { margin-top: 0px; padding-top: 0px; border-color: transparent !important; }
.typora-export * { -webkit-print-color-adjust: exact; }
html.blink-to-pdf { font-size: 13px; }
.typora-export #write { padding-left: 32px; padding-right: 32px; padding-bottom: 0px; break-after: avoid; }
.typora-export #write::after { height: 0px; }
}
.footnote-line { margin-top: 0.714em; font-size: 0.7em; }
a img, img a { cursor: pointer; }
pre.md-meta-block { font-size: 0.8rem; min-height: 0.8rem; white-space: pre-wrap; background: rgb(204, 204, 204); display: block; overflow-x: hidden; }
p > .md-image:only-child:not(.md-img-error) img, p > img:only-child { display: block; margin: auto; }
p > .md-image:only-child { display: inline-block; width: 100%; }
#write .MathJax_Display { margin: 0.8em 0px 0px; }
.md-math-block { width: 100%; }
.md-math-block:not(:empty)::after { display: none; }
[contenteditable="true"]:active, [contenteditable="true"]:focus { outline: 0px; box-shadow: none; }
.md-task-list-item { position: relative; list-style-type: none; }
.task-list-item.md-task-list-item { padding-left: 0px; }
.md-task-list-item > input { position: absolute; top: 0px; left: 0px; margin-left: -1.2em; margin-top: calc(1em - 10px); border: none; }
.math { font-size: 1rem; }
.md-toc { min-height: 3.58rem; position: relative; font-size: 0.9rem; border-radius: 10px; }
.md-toc-content { position: relative; margin-left: 0px; }
.md-toc-content::after, .md-toc::after { display: none; }
.md-toc-item { display: block; color: rgb(65, 131, 196); }
.md-toc-item a { text-decoration: none; }
.md-toc-inner:hover { text-decoration: underline; }
.md-toc-inner { display: inline-block; cursor: pointer; }
.md-toc-h1 .md-toc-inner { margin-left: 0px; font-weight: 700; }
.md-toc-h2 .md-toc-inner { margin-left: 2em; }
.md-toc-h3 .md-toc-inner { margin-left: 4em; }
.md-toc-h4 .md-toc-inner { margin-left: 6em; }
.md-toc-h5 .md-toc-inner { margin-left: 8em; }
.md-toc-h6 .md-toc-inner { margin-left: 10em; }
@media screen and (max-width: 48em) {
.md-toc-h3 .md-toc-inner { margin-left: 3.5em; }
.md-toc-h4 .md-toc-inner { margin-left: 5em; }
.md-toc-h5 .md-toc-inner { margin-left: 6.5em; }
.md-toc-h6 .md-toc-inner { margin-left: 8em; }
}
a.md-toc-inner { font-size: inherit; font-style: inherit; font-weight: inherit; line-height: inherit; }
.footnote-line a:not(.reversefootnote) { color: inherit; }
.md-attr { display: none; }
.md-fn-count::after { content: "."; }
code, pre, samp, tt { font-family: var(--monospace); }
kbd { margin: 0px 0.1em; padding: 0.1em 0.6em; font-size: 0.8em; color: rgb(36, 39, 41); background: rgb(255, 255, 255); border: 1px solid rgb(173, 179, 185); border-radius: 3px; box-shadow: rgba(12, 13, 14, 0.2) 0px 1px 0px, rgb(255, 255, 255) 0px 0px 0px 2px inset; white-space: nowrap; vertical-align: middle; }
.md-comment { color: rgb(162, 127, 3); opacity: 0.8; font-family: var(--monospace); }
code { text-align: left; vertical-align: initial; }
a.md-print-anchor { white-space: pre !important; border-width: initial !important; border-style: none !important; border-color: initial !important; display: inline-block !important; position: absolute !important; width: 1px !important; right: 0px !important; outline: 0px !important; background: 0px 0px !important; text-decoration: initial !important; text-shadow: initial !important; }
.md-inline-math .MathJax_SVG .noError { display: none !important; }
.html-for-mac .inline-math-svg .MathJax_SVG { vertical-align: 0.2px; }
.md-math-block .MathJax_SVG_Display { text-align: center; margin: 0px; position: relative; text-indent: 0px; max-width: none; max-height: none; min-height: 0px; min-width: 100%; width: auto; overflow-y: hidden; display: block !important; }
.MathJax_SVG_Display, .md-inline-math .MathJax_SVG_Display { width: auto; margin: inherit; display: inline-block !important; }
.MathJax_SVG .MJX-monospace { font-family: var(--monospace); }
.MathJax_SVG .MJX-sans-serif { font-family: sans-serif; }
.MathJax_SVG { display: inline; font-style: normal; font-weight: 400; line-height: normal; zoom: 90%; text-indent: 0px; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; }
.MathJax_SVG * { transition: none 0s ease 0s; }
.MathJax_SVG_Display svg { vertical-align: middle !important; margin-bottom: 0px !important; margin-top: 0px !important; }
.os-windows.monocolor-emoji .md-emoji { font-family: "Segoe UI Symbol", sans-serif; }
.md-diagram-panel > svg { max-width: 100%; }
[lang="mermaid"] svg, [lang="flow"] svg { max-width: 100%; height: auto; }
[lang="mermaid"] .node text { font-size: 1rem; }
table tr th { border-bottom: 0px; }
video { max-width: 100%; display: block; margin: 0px auto; }
iframe { max-width: 100%; width: 100%; border: none; }
.highlight td, .highlight tr { border: 0px; }

.CodeMirror { height: auto; }
.CodeMirror.cm-s-inner { background: inherit; }
.CodeMirror-scroll { overflow: auto hidden; z-index: 3; }
.CodeMirror-gutter-filler, .CodeMirror-scrollbar-filler { background-color: rgb(255, 255, 255); }
.CodeMirror-gutters { border-right: 1px solid rgb(221, 221, 221); background: inherit; white-space: nowrap; }
.CodeMirror-linenumber { padding: 0px 3px 0px 5px; text-align: right; color: rgb(153, 153, 153); }
.cm-s-inner .cm-keyword { color: rgb(119, 0, 136); }
.cm-s-inner .cm-atom, .cm-s-inner.cm-atom { color: rgb(34, 17, 153); }
.cm-s-inner .cm-number { color: rgb(17, 102, 68); }
.cm-s-inner .cm-def { color: rgb(0, 0, 255); }
.cm-s-inner .cm-variable { color: rgb(0, 0, 0); }
.cm-s-inner .cm-variable-2 { color: rgb(0, 85, 170); }
.cm-s-inner .cm-variable-3 { color: rgb(0, 136, 85); }
.cm-s-inner .cm-string { color: rgb(170, 17, 17); }
.cm-s-inner .cm-property { color: rgb(0, 0, 0); }
.cm-s-inner .cm-operator { color: rgb(152, 26, 26); }
.cm-s-inner .cm-comment, .cm-s-inner.cm-comment { color: rgb(170, 85, 0); }
.cm-s-inner .cm-string-2 { color: rgb(255, 85, 0); }
.cm-s-inner .cm-meta { color: rgb(85, 85, 85); }
.cm-s-inner .cm-qualifier { color: rgb(85, 85, 85); }
.cm-s-inner .cm-builtin { color: rgb(51, 0, 170); }
.cm-s-inner .cm-bracket { color: rgb(153, 153, 119); }
.cm-s-inner .cm-tag { color: rgb(17, 119, 0); }
.cm-s-inner .cm-attribute { color: rgb(0, 0, 204); }
.cm-s-inner .cm-header, .cm-s-inner.cm-header { color: rgb(0, 0, 255); }
.cm-s-inner .cm-quote, .cm-s-inner.cm-quote { color: rgb(0, 153, 0); }
.cm-s-inner .cm-hr, .cm-s-inner.cm-hr { color: rgb(153, 153, 153); }
.cm-s-inner .cm-link, .cm-s-inner.cm-link { color: rgb(0, 0, 204); }
.cm-negative { color: rgb(221, 68, 68); }
.cm-positive { color: rgb(34, 153, 34); }
.cm-header, .cm-strong { font-weight: 700; }
.cm-del { text-decoration: line-through; }
.cm-em { font-style: italic; }
.cm-link { text-decoration: underline; }
.cm-error { color: red; }
.cm-invalidchar { color: red; }
.cm-constant { color: rgb(38, 139, 210); }
.cm-defined { color: rgb(181, 137, 0); }
div.CodeMirror span.CodeMirror-matchingbracket { color: rgb(0, 255, 0); }
div.CodeMirror span.CodeMirror-nonmatchingbracket { color: rgb(255, 34, 34); }
.cm-s-inner .CodeMirror-activeline-background { background: inherit; }
.CodeMirror { position: relative; overflow: hidden; }
.CodeMirror-scroll { height: 100%; outline: 0px; position: relative; box-sizing: content-box; background: inherit; }
.CodeMirror-sizer { position: relative; }
.CodeMirror-gutter-filler, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-vscrollbar { position: absolute; z-index: 6; display: none; }
.CodeMirror-vscrollbar { right: 0px; top: 0px; overflow: hidden; }
.CodeMirror-hscrollbar { bottom: 0px; left: 0px; overflow: hidden; }
.CodeMirror-scrollbar-filler { right: 0px; bottom: 0px; }
.CodeMirror-gutter-filler { left: 0px; bottom: 0px; }
.CodeMirror-gutters { position: absolute; left: 0px; top: 0px; padding-bottom: 30px; z-index: 3; }
.CodeMirror-gutter { white-space: normal; height: 100%; box-sizing: content-box; padding-bottom: 30px; margin-bottom: -32px; display: inline-block; }
.CodeMirror-gutter-wrapper { position: absolute; z-index: 4; background: 0px 0px !important; border: none !important; }
.CodeMirror-gutter-background { position: absolute; top: 0px; bottom: 0px; z-index: 4; }
.CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; }
.CodeMirror-lines { cursor: text; }
.CodeMirror pre { border-radius: 0px; border-width: 0px; background: 0px 0px; font-family: inherit; font-size: inherit; margin: 0px; white-space: pre; overflow-wrap: normal; color: inherit; z-index: 2; position: relative; overflow: visible; }
.CodeMirror-wrap pre { overflow-wrap: break-word; white-space: pre-wrap; word-break: normal; }
.CodeMirror-code pre { border-right: 30px solid transparent; width: fit-content; }
.CodeMirror-wrap .CodeMirror-code pre { border-right: none; width: auto; }
.CodeMirror-linebackground { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; z-index: 0; }
.CodeMirror-linewidget { position: relative; z-index: 2; overflow: auto; }
.CodeMirror-wrap .CodeMirror-scroll { overflow-x: hidden; }
.CodeMirror-measure { position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden; }
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor { position: absolute; visibility: hidden; border-right: none; width: 0px; }
.CodeMirror div.CodeMirror-cursor { visibility: hidden; }
.CodeMirror-focused div.CodeMirror-cursor { visibility: inherit; }
.cm-searching { background: rgba(255, 255, 0, 0.4); }
@media print {
.CodeMirror div.CodeMirror-cursor { visibility: hidden; }
}

:root { --side-bar-bg-color: #fafafa; --control-text-color: #777; }
html { font-size: 16px; }
body { font-family: "Open Sans", "Clear Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; color: rgb(51, 51, 51); line-height: 1.6; }
#write { max-width: 860px; margin: 0px auto; padding: 30px 30px 100px; }
#write > ul:first-child, #write > ol:first-child { margin-top: 30px; }
a { color: rgb(65, 131, 196); }
h1, h2, h3, h4, h5, h6 { position: relative; margin-top: 1rem; margin-bottom: 1rem; font-weight: bold; line-height: 1.4; cursor: text; }
h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { text-decoration: none; }
h1 tt, h1 code { font-size: inherit; }
h2 tt, h2 code { font-size: inherit; }
h3 tt, h3 code { font-size: inherit; }
h4 tt, h4 code { font-size: inherit; }
h5 tt, h5 code { font-size: inherit; }
h6 tt, h6 code { font-size: inherit; }
h1 { padding-bottom: 0.3em; font-size: 2.25em; line-height: 1.2; border-bottom: 1px solid rgb(238, 238, 238); }
h2 { padding-bottom: 0.3em; font-size: 1.75em; line-height: 1.225; border-bottom: 1px solid rgb(238, 238, 238); }
h3 { font-size: 1.5em; line-height: 1.43; }
h4 { font-size: 1.25em; }
h5 { font-size: 1em; }
h6 { font-size: 1em; color: rgb(119, 119, 119); }
p, blockquote, ul, ol, dl, table { margin: 0.8em 0px; }
li > ol, li > ul { margin: 0px; }
hr { height: 2px; padding: 0px; margin: 16px 0px; background-color: rgb(231, 231, 231); border: 0px none; overflow: hidden; box-sizing: content-box; }
li p.first { display: inline-block; }
ul, ol { padding-left: 30px; }
ul:first-child, ol:first-child { margin-top: 0px; }
ul:last-child, ol:last-child { margin-bottom: 0px; }
blockquote { border-left: 4px solid rgb(223, 226, 229); padding: 0px 15px; color: rgb(119, 119, 119); }
blockquote blockquote { padding-right: 0px; }
table { padding: 0px; word-break: initial; }
table tr { border-top: 1px solid rgb(223, 226, 229); margin: 0px; padding: 0px; }
table tr:nth-child(2n), thead { background-color: rgb(248, 248, 248); }
table tr th { font-weight: bold; border-width: 1px 1px 0px; border-top-style: solid; border-right-style: solid; border-left-style: solid; border-top-color: rgb(223, 226, 229); border-right-color: rgb(223, 226, 229); border-left-color: rgb(223, 226, 229); border-image: initial; border-bottom-style: initial; border-bottom-color: initial; margin: 0px; padding: 6px 13px; }
table tr td { border: 1px solid rgb(223, 226, 229); margin: 0px; padding: 6px 13px; }
table tr th:first-child, table tr td:first-child { margin-top: 0px; }
table tr th:last-child, table tr td:last-child { margin-bottom: 0px; }
.CodeMirror-lines { padding-left: 4px; }
.code-tooltip { box-shadow: rgba(0, 28, 36, 0.3) 0px 1px 1px 0px; border-top: 1px solid rgb(238, 242, 242); }
.md-fences, code, tt { border: 1px solid rgb(231, 234, 237); background-color: rgb(248, 248, 248); border-radius: 3px; padding: 2px 4px 0px; font-size: 0.9em; }
code { background-color: rgb(243, 244, 244); padding: 0px 2px; }
.md-fences { margin-bottom: 15px; margin-top: 15px; padding-top: 8px; padding-bottom: 6px; }
.md-task-list-item > input { margin-left: -1.3em; }
@media print {
html { font-size: 13px; }
table, pre { break-inside: avoid; }
pre { overflow-wrap: break-word; }
}
.md-fences { background-color: rgb(248, 248, 248); }
#write pre.md-meta-block { padding: 1rem; font-size: 85%; line-height: 1.45; background-color: rgb(247, 247, 247); border: 0px; border-radius: 3px; color: rgb(119, 119, 119); margin-top: 0px !important; }
.mathjax-block > .code-tooltip { bottom: 0.375rem; }
.md-mathjax-midline { background: rgb(250, 250, 250); }
#write > h3.md-focus::before { left: -1.5625rem; top: 0.375rem; }
#write > h4.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
#write > h5.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
#write > h6.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
.md-image > .md-meta { border-radius: 3px; padding: 2px 0px 0px 4px; font-size: 0.9em; color: inherit; }
.md-tag { color: rgb(167, 167, 167); opacity: 1; }
.md-toc { margin-top: 20px; padding-bottom: 20px; }
.sidebar-tabs { border-bottom: none; }
#typora-quick-open { border: 1px solid rgb(221, 221, 221); background-color: rgb(248, 248, 248); }
#typora-quick-open-item { background-color: rgb(250, 250, 250); border-color: rgb(254, 254, 254) rgb(229, 229, 229) rgb(229, 229, 229) rgb(238, 238, 238); border-style: solid; border-width: 1px; }
.on-focus-mode blockquote { border-left-color: rgba(85, 85, 85, 0.12); }
header, .context-menu, .megamenu-content, footer { font-family: "Segoe UI", Arial, sans-serif; }
.file-node-content:hover .file-node-icon, .file-node-content:hover .file-node-open-state { visibility: visible; }
.mac-seamless-mode #typora-sidebar { background-color: var(--side-bar-bg-color); }
.md-lang { color: rgb(180, 101, 77); }
.html-for-mac .context-menu { --item-hover-bg-color: #E6F0FE; }
#md-notification .btn { border: 0px; }
.dropdown-menu .divider { border-color: rgb(229, 229, 229); }
.ty-preferences .window-content { background-color: rgb(250, 250, 250); }
.ty-preferences .nav-group-item.active { color: white; background: rgb(153, 153, 153); }
-->

Python学习day37-并发编程(3)

进程锁Lock

上文中我们提到抢票软件的原理,其实还可以做一个小优化,具体就要用到进程锁这个模块,进程锁可以起到和join相同的作用,但是有区别.

 
 
 
xxxxxxxxxx
2
 
 
 
 
1
* join是吧所有的子进程变成了串行
2
* 进程锁则是把锁住的代码变成了串行,相比之下进程锁更加方便,实用性泛用性也更强
 
 

示例代码如下:

 
 
 
xxxxxxxxxx
43
 
 
 
 
1
from multiprocessing import Process, Lock
2
import time
3
import json
4
import os
5
6
7
def search():
8
    time.sleep(1)  # 模拟网络io
9
    with open('db.txt', 'rt', encoding='utf-8')as f:
10
        res = json.load(f)
11
        print(f'还剩{res["count"]}张票')
12
13
14
def get():
15
    with open('db.txt', 'rt', encoding='utf-8')as f:
16
        res = json.load(f)
17
        # print(f'还剩{res["count"]}张票')
18
    time.sleep(1)  # 模拟网络io
19
    if res['count'] > 0:
20
        res['count'] -= 1
21
        with open('db.txt', 'wt', encoding='utf-8')as f:
22
            json.dump(res, f)
23
            f.flush()
24
            print(f'{os.getpid()}抢票成功')
25
            time.sleep(1)  # 模拟网络io
26
27
    else:
28
        print('票已经售空!~!~!~!~!~!~!~!')
29
30
31
def task(lock):
32
    # search()
33
    lock.acquire()  # 进程锁锁住,同一时间只能拿有一个用于执行get函数,也就是购买函数
34
    get()
35
    lock.release()  # 释放锁,下一个用户可以操作
36
37
38
if __name__ == '__main__':
39
    lock = Lock()  # 写在main里面,主进程里,让子进程拿到同一把锁
40
    for i in range(5):
41
        p = Process(target=task, args=(lock,))
42
        p.start()
43
        # p.join()# 因为加入了进程锁,所以join用来串行子进程的方式就可以弃用了
 
 

以上方法虽然相比之前有了一定的改进,但实际上还是很麻烦,并不适用于并发数量较多的情况,而且一方面效率比较低,另外一方面需要自己加锁处理.

所以其实我们还有一种更好更方便的方式来解决这个问题,就是队列Queue.

Queue队列

首先我们了解一下进程间通信的概念即可,简称是IPC,全称是Inter-Process Communication,就是字面意思,进程之间的通信,我们通常会采用Queue队列的方式.

队列的概念其实就是管道pipe加进程锁lock,其作用局势创建共享的进程队列,从而来实现进程之间的通信以及数据传递,实际上队列里面一般不会放入比较大的数据,大部分时候都是消息或者是一些非常小的数据.

Queue(maxsize)就是创建队列的方法,下面我们来看一下队列Queue的部分源码,笔者已经把那些复杂的实现原理删掉,我们只需要了解其有什么参数以及怎么使用就好:

 
 
 
xxxxxxxxxx
35
 
 
 
 
1
class Queue(object):
2
3
    def __init__(self, maxsize=0, *, ctx):
4
        pass
5
    # 这里maxsize = 0就是队列的最大长度,如果没有手动赋值的话队列就不限长度.
6
    def put(self, obj, block=True, timeout=None):
7
pass
8
    # 这里,put方法,最常用的方法之一,将值放入队列中
9
    # 其中的参数,obj即为要放入的值
10
    # block是一种阻塞状态,默认为True,即阻塞,阻塞的意思就是如果队列长度已经满了,put不能放值进去,那么这个方法就会停止,不会继续向下执行.
11
    # timeout即为时间延时,延时就是put方法在这些时间之内如果不能成功给队列放入值就会报错.要注意的是如果block为False的话延时是没有作用的,因为此时方法不具有阻塞作用,所以延时自然是无效的.
12
13
    def get(self, block=True, timeout=None):
14
        pass
15
    # get,即是从队列中取值,其参数和用法和put完全一样,只是我们不用往里面放值而是按之前put进去的顺序往外取值.block和timeout的含义也和上面put一样
16
17
    def qsize(self):
18
        return self._maxsize - self._sem._semlock._get_value()
19
# 这个方法可以返回队列中的值的数量,但并非可靠值,因为队列中值会在不断的变化,使用时候要注意
20
    def empty(self):
21
        return not self._poll()
22
# 判断队列是否为空,返回值为布尔值True或者False
23
    def full(self):
24
        return self._sem._semlock._is_zero()
25
# 判断队列是否已经满了,返回值为布尔值True或者False
26
    def get_nowait(self):
27
        return self.get(False)
28
# 用法等同于get,但是没有block参数,相当于block = False
29
    def put_nowait(self, obj):
30
        return self.put(obj, False)
31
# 用法等同于put,但是没有block参数,相当于block = False
32
    def close(self):
33
pass
34
    # 字面意思,关闭当前队列,防止队列中加入更多的数据
35
 
 

生产者消费者模型

  • 生产者:生产数据的任务

  • 消费者:处理数据的任务

    生产者<-->队列<-->消费者

    生产者可以不停地生产,可以达到自己最大的生产效率 消费者可以不停的消费,也达到了自己最大的消费效率生产者消费者模型: 大大提高了生产者生产的效率和消费者消费的效率

    所以在并发编程中,使用生产者和消费者模型可以解决绝大多数的并发问题.这个模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度.

    要注意的一点是,队列Queue并不适合传输大型的数据或文件,通常应该传递消息之类,上文中也有提到.

    以下为生产者和消费者的一个示例:

     
     
     
    x
     
     
     
     
    1
    from multiprocessing import Process, Queue
    2
    3
    4
    def producer(q, name, food):
    5
        '''生产者函数'''
    6
        for i in range(3):
    7
            print(f'{name}生产出来{food}{i}')
    8
            res = f'{food}{i}'
    9
            q.put(res)
    10
    11
    12
    def consumer(q, name):
    13
        '''消费者函数'''
    14
        while True:
    15
            res = q.get(timeout=2)
    16
            if res is None:# 这里,当取到队列中的值是None时,跳出循环,即消费者停止消费
    17
                print(f'{name}没东西了,木法吃了')
    18
                break
    19
            print(f'{name}吃了{res}')
    20
    21
    22
    if __name__ == '__main__':
    23
        q = Queue()
    24
        p1 = Process(target=producer, args=(q, 'rocky', '包子'))
    25
        p2 = Process(target=producer, args=(q, 'tank', '韭菜'))
    26
        p3 = Process(target=producer, args=(q, 'nick', '蒜泥'))
    27
        c1 = Process(target=consumer, args=(q, '111'))
    28
        c2 = Process(target=consumer, args=(q, '222'))
    29
        p1.start()
    30
        p2.start()
    31
        p3.start()
    32
        c1.start()
    33
        c2.start()
    34
        p1.join()
    35
        p2.join()
    36
        p3.join()
    37
        q.put(None)# 为什么这里要加入两个None呢,为了让两个消费者都能成功的跳出消费循环,不至于到最后报错队列为空.
    38
        q.put(None)
    39
     
     

    其实这种处理方式有点傻,试想一下,如果这样处理生产者和消费者之间的关系,那么每多一个消费者我们就要多在队列里加入一个None,这样会非常的麻烦,而且代码也会显得非常的low.

    所以我们可以借用JoinableQueue来完成这个事情.

JoinableQueue

JoinableQueue的用法和Queue非常的相似,但是有些许不同,让我们来看下JoinableQueue的源码如何:

 
 
 
x
 
 
 
 
1
class JoinableQueue(Queue):
2
3
    def __init__(self, maxsize=0, *, ctx):
4
pass
5
    # 我们可以看到,JoinableQueue的自身init里面和Queue基本上一模一样
6
7
    def put(self, obj, block=True, timeout=None):
8
pass
9
    # put的用法和Queue一样,参数也一样
10
11
    def task_done(self):
12
pass
13
# 这个就是JoinableQueue和Queue最大的不同之一,我们可以看到,JoinableQueue里面并没有get方法,所以在调用get方法的时候是调用的JoinableQueue父类,也就是Queue的get方法.
14
    # 而task_done的意义就是使用者调用此方法的时候会发出一个信号,表示q.get()返回的项目已经被处理掉了.
15
    def join(self):
16
pass
17
    # 这里的join同样为阻塞作用,不同的是在JoinableQueue里面,我们调用这个方法的时候会阻塞直到队列里所有的项目都会处理掉.处理掉的意思就是在所有的q.get()下面都要加上task_done的调用,这样join才会不再阻塞程序的运行.
18
19
# 上述概念我们可以理解为一个计数器
20
# 对这个计数器来说:
21
#    put +1的操作
22
#    task_done -1的操作
23
# q.task_done()   完成了一次任务,和get连用,减少计数器的计数
24
# q.join()    计数器为零才会不阻塞
 
 

那么,采用JoinableQueue改造过上面的生产者消费者模型的小实例为:

 
 
 
x
 
 
1
from multiprocessing import Process,  JoinableQueue
2
import time, random
3
4
5
def producer(q, name, food):
6
    '''生产者函数'''
7
    for i in range(3):
8
        time.sleep(2 * random.random())
9
        print(f'{name}生产出来{food}{i}')
10
        res = f'{food}{i}'
11
        q.put(res)
12
13
14
def consumer(q, name):
15
    '''消费者函数'''
16
    while True:
17
        res = q.get()
18
        time.sleep(2 * random.random())
19
        # if res is None:# 因为判定方式变了,我们没有向队列里加入None,所以这个判断无效了
20
        #     print(f'{name}没东西了,木法吃了')
21
        #     break
22
        print(f'{name}吃了{res}')
23
        q.task_done()# 这里是相当于队列的计数器减一
24
25
26
if __name__ == '__main__':
27
    q = JoinableQueue()
28
    p1 = Process(target=producer, args=(q, 'rocky', '包子'))
29
    p2 = Process(target=producer, args=(q, 'tank', '韭菜'))
30
    p3 = Process(target=producer, args=(q, 'nick', '蒜泥'))
31
    c1 = Process(target=consumer, args=(q, '111'), daemon=True)
32
    c2 = Process(target=consumer, args=(q, '222'), daemon=True)
33
    # 这里在消费者的子进程生成时我们将其定义为守护进程,这样主进程在执行完毕后子进程就会随之结束,我们就不用再每添加一个消费者就要往队列里添加一个None了.
34
    p1.start()
 
 
35
    p2.start()
36
    p3.start()
37
    c1.start()
38
    c2.start()
39
    p1.join()
40
    p2.join()
41
    p3.join()  # 生产者生产完毕
42
    q.join()  # 这里是主进程的最后一行代码
43
    # 所以把消费者c1,c2做成守护进程的话,主进程最后一行一旦执行通过(q.join()通过也就是队列为空),就可以结束子进程,也就是消费者的两个子进程就会结束
 
 

Python学习day37-并发编程(3)的更多相关文章

  1. python学习之并发编程

    目录 一.并发编程之多进程 1.multiprocessing模块介绍 2.Process类的介绍 3.Process类的使用 3.1 创建开启子进程的两种方式 3.2 获取进程pid 3.3验证进程 ...

  2. python学习之并发编程(理论部分)

    第一章 操作系统 管理控制协调计算机中硬件与软件的关系. 操作系统的作用? 第一个作用: 将一些对硬件操作的复杂丑陋的接口,变成简单美丽的接口. open函数. 第二个作用: 多个进程抢占一个(CPU ...

  3. Python学习day40-并发编程(终)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  4. Python学习day39-并发编程(各种锁)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  5. Python学习day38-并发编程(线程)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  6. Python学习day35-并发编程(1)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  7. Python中的并发编程

    简介 我们将一个正在运行的程序称为进程.每个进程都有它自己的系统状态,包含内存状态.打开文件列表.追踪指令执行情况的程序指针以及一个保存局部变量的调用栈.通常情况下,一个进程依照一个单序列控制流顺序执 ...

  8. python学习_数据处理编程实例(二)

    在上一节python学习_数据处理编程实例(二)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年 ...

  9. Python学习之==>面向对象编程(二)

    一.类的特殊成员 我们在Python学习之==>面向对象编程(一)中已经介绍过了构造方法和析构方法,构造方法是在实例化时自动执行的方法,而析构方法是在实例被销毁的时候被执行,Python类成员中 ...

随机推荐

  1. android 自定义shape 带阴影边框效果

    在drawable 里面 建立一个 xml 直接复制 看效果 自己调试就可以 <?xml version="1.0" encoding="utf-8"?& ...

  2. P1820 寻找AP数

    P1820 寻找AP数两个性质,分解质因数后,连续,且指数递减,dfs就完了 #include <iostream> #include <cstdio> #include &l ...

  3. 校园商铺-4店铺注册功能模块-6店铺注册之Controller层的实现

    1. 从request请求获取获取相关的值 HttpservletRequest request代表的是客户端的请求.当客户端通过http协议访问服务器的时候,http请求头中的所有信息,都封装在这个 ...

  4. QQ空间删除日志

    按下F12,贴上如下代码 var delay = 2000; function del() { document.querySelector(".app_canvas_frame" ...

  5. 分享一些PPT模板

     链接:https://pan.baidu.com/s/1ADlYzx7sWR2z0ltVt8kIAQ 提取码:tyzv  

  6. Android_Gallery(画廊)

    转:http://blog.csdn.net/tianjf0514/article/details/7521398 Gallery是画廊的意思,可以实现图片的浏览功能. 主要内容 Gallery控件的 ...

  7. idea运行tomcat,控制台中文乱码

    加入参数:-Dfile.encoding=UTF-8

  8. IntelliJ IDEA更换主题样式分享

    原文地址:https://blog.csdn.net/liu865033503/article/details/79481785 .自定义主题样式网址:http://www.riaway.com/in ...

  9. 用原生js封装轮播图

    原生js封装轮播图 对于初学js的同学来说,轮播图还是一个难点,尤其是原生js封装轮播图代码,下面是我之前做的一个轮播图项目中封装好的一些代码,有需要的同学可以看一下,有什么不懂的可以看注释,注释看不 ...

  10. 响应式编程(Reactive Programming)(Rx)介绍

    很明显你是有兴趣学习这种被称作响应式编程的新技术才来看这篇文章的. 学习响应式编程是很困难的一个过程,特别是在缺乏优秀资料的前提下.刚开始学习时,我试过去找一些教程,并找到了为数不多的实用教程,但是它 ...