File tree Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ import _thread
2
+
3
+ def action (i ):
4
+ print (i ** 32 )
5
+
6
+ class Power :
7
+ def __init__ (self , i ):
8
+ self .i = i
9
+ def action (self ): # bound method runs in thread
10
+ print (self .i ** 32 )
11
+
12
+ _thread .start_new_thread (action , (2 ,)) # simple function
13
+
14
+ _thread .start_new_thread ((lambda : action (2 )), ()) # lambda function to defer
15
+
16
+ obj = Power (2 )
17
+ _thread .start_new_thread (obj .action , ()) # bound method object
Original file line number Diff line number Diff line change
1
+ import _thread as thread , time
2
+
3
+ """
4
+ thread basics: start 5 copies of a function running in parallel;
5
+ uses time.sleep so that the main thread doesn't die too early--
6
+ this kills all other threads on some platforms; stdout is shared:
7
+ thread outputs may be intermixed in this version arbitarily.
8
+ """
9
+
10
+ def counter (myId , count ):
11
+ for i in range (count ):
12
+ time .sleep (1 )
13
+ print ('[%s] => %s' % (myId , i ))
14
+
15
+ for i in range (5 ): # spawns 5 threads
16
+ thread .start_new_thread (counter , (i , 5 )) # each thread loops 5 times
17
+
18
+ time .sleep (6 )
19
+ print ('Main thread exiting.' ) # don't exit too early
Original file line number Diff line number Diff line change
1
+ # use python3
2
+ """
3
+ spawns thread until we type 'q'
4
+ """
5
+
6
+ import _thread
7
+
8
+ def child (tid ):
9
+
10
+ print ("Hello from thread" , tid )
11
+
12
+ def parent ():
13
+ i = 0
14
+ while True :
15
+ i += 1
16
+ _thread .start_new_thread (child , (i ,))
17
+ if input ()== 'q' : break
18
+
19
+ parent ()
You can’t perform that action at this time.
0 commit comments