Threading
Matt
matt.mailinglists at gmail.com
Fri Jan 24 19:12:12 EST 2020
> Not quite.
>
> 1. Create a list of threads.
>
> 2. Put the items into a _queue_, not a list.
>
> 3. Start the threads.
>
> 4. Iterate over the list of threads, using .join() on each.
>
> If you're going to start the threads before you've put all of the items
> into the queue, you can also put a sentinel such as None into the queue
> after you've finished putting the items into it. When a thread sees the
> sentinel, it knows there are no more items to come. You could have one
> sentinel for each thread, or have only one and have each thread put it
> back when it sees it, for the other threads to see.
>
Is the list not thread safe and I need to use Queue instead or is it
just that using a Queue is more efficient? I think I have everything
else you mentioned changed. Even in python3 now though I still need to
work in python2 in places for time being. Thanks.
import time
import datetime
import threading
import random
big_list = []
def date_stamp():
return "[" + datetime.datetime.now().strftime('%Y-%m-%d
%H:%M:%S:%f')[:-3] + "] "
for i in range(1, 5000):
big_list.append(i)
def start_test(id):
while big_list:
list_item = big_list.pop()
print(date_stamp(), "Thread", id, ":", list_item, port)
time.sleep(random.random())
print(date_stamp(), "Thread", id, "done...")
print(date_stamp(), "Creating Threads...")
port = 80
threads = []
for i in range(1, 10):
t = threading.Thread(target=start_test, args=(i,))
print(date_stamp(), "Starting Thread:", i)
t.start()
threads.append(t)
print(date_stamp(), "Waiting on Threads...")
for t in threads:
t.join()
print(date_stamp(), "Finished...")
More information about the Python-list
mailing list