Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 311959
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T07:58:21+00:00 2026-05-12T07:58:21+00:00

In the following code, you see that pickledList is being used by the thread

  • 0

In the following code, you see that pickledList is being used by the thread and is set in the global scope.

If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possible that its value could change before the thread got to use it? How can I set a value dynamically in the loop, send it off to the thread and make sure that its value doesn’t change before the thread gets to use 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 a better example of my problem. If you run this, sometimes the values change before the thread can output them, causing some to 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()

How can I pass the value in i to the thread in such a way that its no longer bound to the variable, so that if the value stored in i changes, the value the thread is working with is not affected.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T07:58:21+00:00Added an answer on May 12, 2026 at 7:58 am

    Option 1: you can pass arguments into each Thread when it is instantiated:

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

    in which case your run method will be called:

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

    by the Thread instance when you call start(). If you need to pass mutable objects (dicts, lists, instances) to the function, you must be sure to re-assign the global variable, not edit it in place.

    Option 2: you can set an instance variable on your ClientThread objects:

    myThread.setMyAttribute('new value')
    

    With option 2 you need to be wary of race conditions etc. depending on what the method does. Using Locks whenever you’re writing or reading data from/to a thread is a good idea.

    Option 3: grab the global when run is first called and store a copy locally

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

    Option 1 is the right way to go if the value a thread is given never needs to change during its lifetime, Option 2 if the value does need to change. Option 3 is a hack.

    With regard to generally passing variables/values around, you must remember with Python that immutable objects (strings, numbers, tuples) are passed by value and mutable objects (dicts, lists, class instances) are passed by reference.

    Consequently, altering a string, number or tuple will not affect any instances previously passed that variable, however altering a dict, list or instance will do. Re-assigning a variable to a different object will not affect anything previously given the old value.

    Globals certainly shouldn’t be used for values that may change (if at all). Basically your example is doing it the wrong way.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I m having the following code, however, I can see that the radio button
I have a WSP containing a web scope feature with the following code: using
(resolved: see bottom) I have the following code snippet: Protected Sub SqlDataSource1_Inserted(ByVal sender As
The following code illustrates an object literal being assigned, but with no semicolon afterwards:
I am filling DropDown dynamically using AJAX. The DropDown code looks like this: <select
Consider the following code, the first demonstrates that the cleanup executes when we're finished
consider the following code: perl -wne 'chomp;print if m/[^(?:test)]/' I was surprised to see
The following code works fine using (var ctx = new MyEntities()) { var devices
The following code fails to compile stating A local variable named 'st' cannot be
Following code, when compiled and run with g++, prints '1' twice, whereas I expect

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.