python代码笔记3(IO/线程)

#_____________IO

<pre name="code" class="python">from io import StringIO
f = StringIO()#BytesIO  f.write('中文'.encode('utf-8'))
f.write("hello")
f.write(",world")
print(f.getvalue())

import pickle
d = dict(key1='liu',key2=23)
f = open('dump.txt','wb')
pickle.dump(d,f)
f.close
f = open('dump.txt','rb')
d = pickle.load(f)
print(d)

import json
j = json.dumps(d)
print(j)
 
</pre><p></p><p>#Process</p><pre code_snippet_id="1790848" snippet_file_name="blog_20160728_5_6131348" name="code" class="python">from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool()
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close() #不能添加新的process了
    p.join()
    print('All subprocesses done.')

#Lock

import threading,time
apple = 0
lock = threading.Lock()
def eating():
	global apple
	while True:
		lock.acquire()
		try:
			apple = apple - 1
			print("the %s eating one,the apple_num is %d" %(threading.current_thread().name, apple) )
		finally:
			time.sleep(1)
			lock.release()
			

def producing():
	global apple
	while True:
		lock.acquire()
		try:
			apple = apple + 1
			print("the %s producing one,the apple_num is %d" %(threading.current_thread().name, apple))
		finally:
			time.sleep(1)
			lock.release()
t1 = threading.Thread(target = eating ,name = "吃的人")
t2 = threading.Thread(target = producing , name = "做的人")
t1.start()
t2.start()
t1.join()
t2.join()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值