Gennadiy Zlobin avatar Gennadiy Zlobin committed 1c12779

Intial commit

Comments (0)

Files changed (17)

+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>pymultithreading</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.python.pydev.PyDevBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.python.pydev.pythonNature</nature>
+	</natures>
+</projectDescription>
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?eclipse-pydev version="1.0"?>
+
+<pydev_project>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">python</pydev_property>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
+<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
+<path>/pymultithreading/src</path>
+</pydev_pathproperty>
+</pydev_project>
+#!/usr/bin/python
+
+import thread
+import time
+
+# Define a function for the thread
+def print_time( threadName, delay):
+    count = 0
+    while count < 5:
+        time.sleep(delay)
+        count += 1
+        print "%s: %s" % ( threadName, time.ctime(time.time()) )
+
+# Create two threads as follows
+try:
+    thread.start_new_thread( print_time, ("Thread-1", 2, ) )
+    thread.start_new_thread( print_time, ("Thread-2", 4, ) )
+except:
+    print "Error: unable to start thread"
+
+while 1:
+    pass
+import os
+import re
+import time
+import sys
+
+lifeline = re.compile(r"(\d) received")
+report = ("No response","Partial Response","Alive")
+
+print time.ctime()
+
+for host in range(60,70):
+    ip = "192.168.200."+str(host)
+    pingaling = os.popen("ping -q -c2 "+ip,"r")
+    print "Testing ",ip,
+    sys.stdout.flush()
+    while 1:
+        line = pingaling.readline()
+        if not line: break
+        igot = re.findall(lifeline,line)
+        if igot:
+            print report[int(igot[0])]
+
+print time.ctime()
+import os
+import re
+import time
+import sys
+from threading import Thread
+
+class testit(Thread):
+    def __init__ (self,ip):
+        Thread.__init__(self)
+        self.ip = ip
+        self.status = -1
+    def run(self):
+        pingaling = os.popen("ping -q -c2 "+self.ip,"r")
+        while 1:
+            line = pingaling.readline()
+            if not line: break
+            igot = re.findall(testit.lifeline,line)
+            if igot:
+                self.status = int(igot[0])
+
+testit.lifeline = re.compile(r"(\d) received")
+report = ("No response","Partial Response","Alive")
+
+print time.ctime()
+
+pinglist = []
+
+for host in range(60,70):
+    ip = "192.168.200."+str(host)
+    current = testit(ip)
+    pinglist.append(current)
+    current.start()
+
+for pingle in pinglist:
+    pingle.join()
+    print "Status from ",pingle.ip,"is",report[pingle.status]
+
+print time.ctime()
+#!/usr/bin/python
+
+import threading
+import time
+
+exitFlag = 0
+
+class myThread (threading.Thread):
+    def __init__(self, threadID, name, counter):
+        self.threadID = threadID
+        self.name = name
+        self.counter = counter
+        threading.Thread.__init__(self)
+    def run(self):
+        print "Starting " + self.name
+        print_time(self.name, self.counter, 5)
+        print "Exiting " + self.name
+
+def print_time(threadName, delay, counter):
+    while counter:
+        if exitFlag:
+            thread.exit()
+        time.sleep(delay)
+        print "%s: %s" % (threadName, time.ctime(time.time()))
+        counter -= 1
+
+# Create new threads
+thread1 = myThread(1, "Thread-1", 1)
+thread2 = myThread(2, "Thread-2", 2)
+
+# Start new Threads
+thread1.start()
+thread2.run()
+
+while thread2.isAlive():
+    if not thread1.isAlive():
+        exitFlag = 1
+    pass
+print "Exiting Main Thread"
+import Queue
+import threading
+import urllib
+
+def geturl(q, url):
+    q.put(urllib.urlfetch(url).read())
+
+theurls = '''http://example.com/be
+             http://example.de/bi
+             http://example.co.uk/bo'''.split()
+
+q = Queue.Queue()
+
+for u in theurls:
+    t = threading.Thread(target=geturl, args=(q, u))
+    t.daemon = True
+    t.start()
+
+s = q.get()
+print s
+#!/usr/bin/python
+
+import threading
+import time
+
+class myThread (threading.Thread):
+    def __init__(self, threadID, name, counter):
+        self.threadID = threadID
+        self.name = name
+        self.counter = counter
+        threading.Thread.__init__(self)
+    def run(self):
+        print "Starting " + self.name
+        # Get lock to synchronize threads
+        threadLock.acquire()
+        print_time(self.name, self.counter, 3)
+        # Free lock to release next thread
+        threadLock.release()
+
+def print_time(threadName, delay, counter):
+    while counter:
+        time.sleep(delay)
+        print "%s: %s" % (threadName, time.ctime(time.time()))
+        counter -= 1
+
+threadLock = threading.Lock()
+threads = []
+
+# Create new threads
+thread1 = myThread(1, "Thread-1", 1)
+thread2 = myThread(2, "Thread-2", 2)
+
+# Start new Threads
+thread1.start()
+thread2.start()
+
+# Add threads to thread list
+threads.append(thread1)
+threads.append(thread2)
+
+# Wait for all threads to complete
+for t in threads:
+    t.join()
+print "Exiting Main Thread"
+from multiprocessing import Process
+import os
+
+def info(title):
+    print title
+    print 'module name:', __name__
+    print 'parent process:', os.getppid()
+    print 'process id:', os.getpid()
+
+def f(name):
+    info('function f')
+    print 'hello', name
+
+if __name__ == '__main__':
+    info('main line')
+    p = Process(target=f, args=('bob',))
+    p.start()
+    p.join()
+from multiprocessing import Process, Queue
+
+def f(q):
+    q.put([42, None, 'hello'])
+
+if __name__ == '__main__':
+    q = Queue()
+    p = Process(target=f, args=(q,))
+    p.start()
+    print q.get()    # prints "[42, None, 'hello']"
+    p.join()
+from multiprocessing import Process, Pipe
+
+def f(conn):
+    conn.send([42, None, 'hello'])
+    conn.close()
+
+if __name__ == '__main__':
+    parent_conn, child_conn = Pipe()
+    p = Process(target=f, args=(child_conn,))
+    p.start()
+    print parent_conn.recv()   # prints "[42, None, 'hello']"
+    p.join()
+from multiprocessing import Process, Lock
+
+def f(l, i):
+    l.acquire()
+    print 'hello world', i
+    l.release()
+
+if __name__ == '__main__':
+    lock = Lock()
+
+    for num in range(10):
+        Process(target=f, args=(lock, num)).start()
+from multiprocessing import Process, Value, Array
+
+def f(n, a):
+    n.value = 3.1415927
+    for i in range(len(a)):
+        a[i] = -a[i]
+
+if __name__ == '__main__':
+    num = Value('d', 0.0)
+    arr = Array('i', range(10))
+
+    p = Process(target=f, args=(num, arr))
+    p.start()
+    p.join()
+
+    print num.value
+    print arr[:]
+from multiprocessing import Process, Manager
+
+def f(d, l):
+    d[1] = '1'
+    d['2'] = 2
+    d[0.25] = None
+    l.reverse()
+
+if __name__ == '__main__':
+    manager = Manager()
+
+    d = manager.dict()
+    l = manager.list(range(10))
+
+    p = Process(target=f, args=(d, l))
+    p.start()
+    p.join()
+
+    print d
+    print l
+from multiprocessing import Pool
+
+def f(x):
+    return x*x
+
+if __name__ == '__main__':
+    pool = Pool(processes=4)              # start 4 worker processes
+    result = pool.apply_async(f, [10])     # evaluate "f(10)" asynchronously
+    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
+    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"
+from multiprocessing import Process, Lock
+from multiprocessing.sharedctypes import Value, Array
+from ctypes import Structure, c_double
+
+class Point(Structure):
+    _fields_ = [('x', c_double), ('y', c_double)]
+
+def modify(n, x, s, A):
+    n.value **= 2
+    x.value **= 2
+    s.value = s.value.upper()
+    for a in A:
+        a.x **= 2
+        a.y **= 2
+
+if __name__ == '__main__':
+    lock = Lock()
+
+    n = Value('i', 7)
+    x = Value(c_double, 1.0/3.0, lock=False)
+    s = Array('c', 'hello world', lock=lock)
+    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
+
+    p = Process(target=modify, args=(n, x, s, A))
+    p.start()
+    p.join()
+
+    print n.value
+    print x.value
+    print s.value
+    print [(a.x, a.y) for a in A]
+#!/usr/bin/python
+
+import Queue
+import threading
+import time
+
+exitFlag = 0
+
+class myThread (threading.Thread):
+    def __init__(self, threadID, name, q):
+        self.threadID = threadID
+        self.name = name
+        self.q = q
+        threading.Thread.__init__(self)
+    def run(self):
+        print "Starting " + self.name
+        process_data(self.name, self.q)
+        print "Exiting " + self.name
+
+def process_data(threadName, q):
+    while not exitFlag:
+        queueLock.acquire()
+        if not workQueue.empty():
+            data = q.get()
+            queueLock.release()
+            print "%s processing %s" % (threadName, data)
+        else:
+            queueLock.release()
+        time.sleep(1)
+
+threadList = ["Thread-1", "Thread-2", "Thread-3"]
+nameList = ["One", "Two", "Three", "Four", "Five"]
+queueLock = threading.Lock()
+workQueue = Queue.Queue(10)
+threads = []
+threadID = 1
+
+# Create new threads
+for tName in threadList:
+    thread = myThread(threadID, tName, workQueue)
+    thread.start()
+    threads.append(thread)
+    threadID += 1
+
+# Fill the queue
+queueLock.acquire()
+for word in nameList:
+    workQueue.put(word)
+queueLock.release()
+
+# Wait for queue to empty
+while not workQueue.empty():
+    pass
+
+# Notify threads it's time to exit
+exitFlag = 1
+
+# Wait for all threads to complete
+for t in threads:
+    t.join()
+print "Exiting Main Thread"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.