A variable with global reach: can its change change before it is raised by the stream?

In the following code, you see what pickledListis being used by the stream and installed in the global scope.

If the variable that the stream uses was dynamically set somewhere below in this final while loop, is it possible that its value can change before the stream gets to use it? How can I set the value dynamically in a loop, send it to the stream and make sure that its value does not change before the stream uses it?

import pickle
import Queue
import socket
import threading

someList = [ 1, 2, 7, 9, 0 ]
pickledList = pickle.dumps ( someList )

class ClientThread ( threading.Thread ):
   def run ( self ):
      while True:
         client = clientPool.get()
         if client != None:
            print 'Received connection:', client [ 1 ] [ 0 ]
            client [ 0 ].send ( pickledList )
            for x in xrange ( 10 ):
               print client [ 0 ].recv ( 1024 )
            client [ 0 ].close()
            print 'Closed connection:', client [ 1 ] [ 0 ]


clientPool = Queue.Queue ( 0 )

for x in xrange ( 2 ):
   ClientThread().start()

server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )

while True:
   clientPool.put ( server.accept() )

EDIT:

Here is the best example of my problem. If you run this, sometimes the values ​​change before the thread outputs them, as a result of which some will be skipped:

from threading import Thread
class t ( Thread ):
    def run(self):
        print "(from thread) ",
        print i

for i in range(1, 50):    
    print i
    t().start()

i , , , , i, , , , .

+3
1

1: :

ClientThread(arg1, arg2, kwarg1="three times!").start()

run:

run(arg1, arg2, kwarg1="three times!")

Thread, start(). (dicts, lists, ) , not, .

2: ClientThread:

myThread.setMyAttribute('new value')

2 .., , . Lock , / , .

3: , run

run(self):
    localVar = globalVar # only for immutable types
    localList = globalList[:] # copy of a list
    localDict = globalDict.copy() # Warning! Shallow copy only!

1 - , , , , 2, . 3 - .

/ , Python, (, , ) (dicts, lists, ) .

, , - , , dict, . .

, , , ( ). .

+3

Source: https://habr.com/ru/post/1714323/


All Articles