Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from copy import deepcopy, copy
- from pdb import set_trace as st
- from os import fork, pipe, read, write, close, fdopen
- from sys import exit
- import sys
- reload(sys)
- sys.setdefaultencoding('utf8')
- THREADS = 4
- LEN = 6
- STEP = 1
- pids = []
- def list_to_str(lst):
- out = ""
- for i in lst:
- out += str(i)
- return out
- STR = list()
- def generate_str():
- global STR, STEP
- STR[len(STR)-1] += STEP
- while STR[len(STR)-1] > 9:
- # for i in reversed(xrange(STR))
- i=len(STR)-1
- while STR[i]>9 and i>0:
- STR[i] -= 10
- STR[i-1] += 1
- i -= 1
- # return copy(STR)
- return STR
- def check_str_loop():
- global STR
- flag1=0
- flag2=0
- res =0
- for i in xrange(len(STR)-1):
- if STR[i] > STR[i+1]:
- flag1+=1
- if STR[i] < STR[i+1]:
- flag2+=1
- if flag1 == len(STR)-1:
- res+=1
- if flag2 == len(STR)-1:
- res+=1
- return res
- def main():
- global STR, STEP, ID, pids
- def truth(str):
- if int(str[0]) > 9:
- return 0
- else:
- return 1
- for i in xrange(THREADS):
- r, w = pipe()
- # r, w = fdopen(r,'r'), fdopen(w,'w')
- p = fork()
- if p == 0:
- str = STR
- avg = 0.0
- index = 0
- STEP = THREADS
- for j in xrange(LEN):
- STR.append(0)
- buf = copy(i)
- iter = len(STR)-1
- while not buf == 0 and not iter == 0:
- STR[iter] = buf%10
- buf /= 10
- iter -= 1
- # print list_to_str(STR)
- while truth(str):
- str = generate_str()
- status = check_str_loop()
- # print "cur: %s\r" % (list_to_str(str)),
- if status > 0:
- # print "%s\r" % (" "*20),
- # print list_to_str(str)
- avg += float(list_to_str(str))
- index += 1
- # print "sum: %.2f" % (avg)
- # print "ind: %i" % (index)
- # print "avg: %.2f" % (avg/index)
- close(r)
- write(w, "%i;%.2f" % (index, avg))
- sys.exit(0)
- else:
- pids.append([])
- pids[i].append(p)
- pids[i].append([r,w])
- # now working in parent thread:
- result = {"avg":0.0, "i":0}
- for i in xrange(THREADS):
- # pids[i][1][1].close()
- close(pids[i][1][1])
- str = read(pids[i][1][0], 4096).split(";")
- result['avg'] += float(str[1])
- result['i'] += int(str[0])
- print "sum: %.2f" % (result['avg'])
- print "ind: %i" % (result['i'])
- print "avg: %.2f" % (result['avg']/result['i'])
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement