Commit 2067bfdf authored by Georg Brandl's avatar Georg Brandl

Rename thread to _thread and dummy_thread to _dummy_thread. Issue #2875.

parent 3b4b45bf
...@@ -4,7 +4,7 @@ This metaclass makes it possible to declare synchronized methods. ...@@ -4,7 +4,7 @@ This metaclass makes it possible to declare synchronized methods.
""" """
import thread import _thread as thread
# First we need to define a reentrant lock. # First we need to define a reentrant lock.
# This is generally useful and should probably be in a standard Python # This is generally useful and should probably be in a standard Python
......
...@@ -12,7 +12,7 @@ can log in on your machine. Use with caution! ...@@ -12,7 +12,7 @@ can log in on your machine. Use with caution!
""" """
import sys, os, string, getopt, thread, socket, traceback import sys, os, string, getopt, _thread, socket, traceback
PORT = 4000 # Default port PORT = 4000 # Default port
...@@ -52,17 +52,17 @@ def main_thread(port): ...@@ -52,17 +52,17 @@ def main_thread(port):
conn.close() conn.close()
print("Refusing connection from non-local host", addr[0], ".") print("Refusing connection from non-local host", addr[0], ".")
continue continue
thread.start_new_thread(service_thread, (conn, addr)) _thread.start_new_thread(service_thread, (conn, addr))
del conn, addr del conn, addr
def service_thread(conn, addr): def service_thread(conn, addr):
(caddr, cport) = addr (caddr, cport) = addr
print("Thread %s has connection from %s.\n" % (str(thread.get_ident()), print("Thread %s has connection from %s.\n" % (str(_thread.get_ident()),
caddr), end=' ') caddr), end=' ')
stdin = conn.makefile("r") stdin = conn.makefile("r")
stdout = conn.makefile("w", 0) stdout = conn.makefile("w", 0)
run_interpreter(stdin, stdout) run_interpreter(stdin, stdout)
print("Thread %s is done.\n" % str(thread.get_ident()), end=' ') print("Thread %s is done.\n" % str(_thread.get_ident()), end=' ')
def run_interpreter(stdin, stdout): def run_interpreter(stdin, stdout):
globals = {} globals = {}
......
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
# current implementation consumes a thread for each coroutine that # current implementation consumes a thread for each coroutine that
# may be resumed. # may be resumed.
import thread import _thread as thread
import sync import sync
class _CoEvent: class _CoEvent:
......
# Generator implementation using threads # Generator implementation using threads
import thread import _thread as thread
Killed = 'Generator.Killed' Killed = 'Generator.Killed'
......
...@@ -20,7 +20,7 @@ import getopt ...@@ -20,7 +20,7 @@ import getopt
import time import time
import os import os
from stat import * from stat import *
import thread import _thread as thread
# Work queue class. Usage: # Work queue class. Usage:
......
...@@ -268,7 +268,7 @@ ...@@ -268,7 +268,7 @@
# if there are are no threads waiting to write. (This is a # if there are are no threads waiting to write. (This is a
# weakness of the interface!) # weakness of the interface!)
import thread import _thread as thread
class condition: class condition:
def __init__(self, lock=None): def __init__(self, lock=None):
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
import sys, os, time import sys, os, time
from socket import * from socket import *
import thread import _thread as thread
BUFSIZE = 8*1024 BUFSIZE = 8*1024
......
...@@ -351,7 +351,7 @@ in various ways. There is a separate error indicator for each thread. ...@@ -351,7 +351,7 @@ in various ways. There is a separate error indicator for each thread.
be raised. It may be called without holding the interpreter lock. be raised. It may be called without holding the interpreter lock.
.. % XXX This was described as obsolete, but is used in .. % XXX This was described as obsolete, but is used in
.. % thread.interrupt_main() (used from IDLE), so it's still needed. .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
.. cfunction:: int PySignal_SetWakeupFd(int fd) .. cfunction:: int PySignal_SetWakeupFd(int fd)
......
...@@ -539,7 +539,7 @@ supports the creation of additional interpreters (using ...@@ -539,7 +539,7 @@ supports the creation of additional interpreters (using
This is a no-op when called for a second time. It is safe to call this function This is a no-op when called for a second time. It is safe to call this function
before calling :cfunc:`Py_Initialize`. before calling :cfunc:`Py_Initialize`.
.. index:: module: thread .. index:: module: _thread
When only the main thread exists, no lock operations are needed. This is a When only the main thread exists, no lock operations are needed. This is a
common situation (most Python programs do not use threads), and the lock common situation (most Python programs do not use threads), and the lock
...@@ -547,7 +547,7 @@ supports the creation of additional interpreters (using ...@@ -547,7 +547,7 @@ supports the creation of additional interpreters (using
initially. This situation is equivalent to having acquired the lock: when initially. This situation is equivalent to having acquired the lock: when
there is only a single thread, all object accesses are safe. Therefore, when there is only a single thread, all object accesses are safe. Therefore, when
this function initializes the lock, it also acquires it. Before the Python this function initializes the lock, it also acquires it. Before the Python
:mod:`thread` module creates a new thread, knowing that either it has the lock :mod:`_thread` module creates a new thread, knowing that either it has the lock
or the lock hasn't been created yet, it calls :cfunc:`PyEval_InitThreads`. When or the lock hasn't been created yet, it calls :cfunc:`PyEval_InitThreads`. When
this call returns, it is guaranteed that the lock has been created and that the this call returns, it is guaranteed that the lock has been created and that the
calling thread has acquired it. calling thread has acquired it.
......
...@@ -488,7 +488,7 @@ type objects) *must* have the :attr:`ob_size` field. ...@@ -488,7 +488,7 @@ type objects) *must* have the :attr:`ob_size` field.
reference cycles. A typical implementation of a :attr:`tp_traverse` function reference cycles. A typical implementation of a :attr:`tp_traverse` function
simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python
objects. For example, this is function :cfunc:`local_traverse` from the objects. For example, this is function :cfunc:`local_traverse` from the
:mod:`thread` extension module:: :mod:`_thread` extension module::
static int static int
local_traverse(localobject *self, visitproc visit, void *arg) local_traverse(localobject *self, visitproc visit, void *arg)
......
:mod:`_dummy_thread` --- Drop-in replacement for the :mod:`_thread` module
==========================================================================
:mod:`dummy_thread` --- Drop-in replacement for the :mod:`thread` module .. module:: _dummy_thread
======================================================================== :synopsis: Drop-in replacement for the _thread module.
.. module:: dummy_thread
:synopsis: Drop-in replacement for the thread module.
This module provides a duplicate interface to the :mod:`_thread` module. It is
This module provides a duplicate interface to the :mod:`thread` module. It is meant to be imported when the :mod:`_thread` module is not provided on a
meant to be imported when the :mod:`thread` module is not provided on a
platform. platform.
Suggested usage is:: Suggested usage is::
try: try:
import thread as _thread import _thread
except ImportError: except ImportError:
import dummy_thread as _thread import dummy_thread as _thread
Be careful to not use this module where deadlock might occur from a thread Be careful to not use this module where deadlock might occur from a thread being
being created that blocks waiting for another thread to be created. This often created that blocks waiting for another thread to be created. This often occurs
occurs with blocking I/O. with blocking I/O.
:mod:`_thread` --- Low-level threading API
==========================================
:mod:`thread` --- Multiple threads of control .. module:: _thread
============================================= :synopsis: Low-level threading API.
.. module:: thread
:synopsis: Create multiple threads of control within one interpreter.
.. index:: .. index::
...@@ -25,8 +24,8 @@ threading API built on top of this module. ...@@ -25,8 +24,8 @@ threading API built on top of this module.
The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris The module is optional. It is supported on Windows, Linux, SGI IRIX, Solaris
2.x, as well as on systems that have a POSIX thread (a.k.a. "pthread") 2.x, as well as on systems that have a POSIX thread (a.k.a. "pthread")
implementation. For systems lacking the :mod:`thread` module, the implementation. For systems lacking the :mod:`_thread` module, the
:mod:`dummy_thread` module is available. It duplicates this module's interface :mod:`_dummy_thread` module is available. It duplicates this module's interface
and can be used as a drop-in replacement. and can be used as a drop-in replacement.
It defines the following constant and functions: It defines the following constant and functions:
...@@ -132,9 +131,9 @@ Lock objects have the following methods: ...@@ -132,9 +131,9 @@ Lock objects have the following methods:
In addition to these methods, lock objects can also be used via the In addition to these methods, lock objects can also be used via the
:keyword:`with` statement, e.g.:: :keyword:`with` statement, e.g.::
import thread import _thread
a_lock = thread.allocate_lock() a_lock = _thread.allocate_lock()
with a_lock: with a_lock:
print("a_lock is locked while this executes") print("a_lock is locked while this executes")
......
:mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module :mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module
============================================================================== ==============================================================================
...@@ -7,17 +6,17 @@ ...@@ -7,17 +6,17 @@
This module provides a duplicate interface to the :mod:`threading` module. It This module provides a duplicate interface to the :mod:`threading` module. It
is meant to be imported when the :mod:`thread` module is not provided on a is meant to be imported when the :mod:`_thread` module is not provided on a
platform. platform.
Suggested usage is:: Suggested usage is::
try: try:
import threading as _threading import threading
except ImportError: except ImportError:
import dummy_threading as _threading import dummy_threading
Be careful to not use this module where deadlock might occur from a thread Be careful to not use this module where deadlock might occur from a thread being
being created that blocks waiting for another thread to be created. This often created that blocks waiting for another thread to be created. This often occurs
occurs with blocking I/O. with blocking I/O.
...@@ -14,10 +14,10 @@ some other systems as well (e.g. Windows or NT). Here's an overview: ...@@ -14,10 +14,10 @@ some other systems as well (e.g. Windows or NT). Here's an overview:
.. toctree:: .. toctree::
select.rst select.rst
thread.rst
threading.rst threading.rst
dummy_thread.rst
dummy_threading.rst dummy_threading.rst
_thread.rst
_dummy_thread.rst
mmap.rst mmap.rst
readline.rst readline.rst
rlcompleter.rst rlcompleter.rst
...@@ -6,12 +6,11 @@ ...@@ -6,12 +6,11 @@
:synopsis: Higher-level threading interface. :synopsis: Higher-level threading interface.
This module constructs higher-level threading interfaces on top of the lower This module constructs higher-level threading interfaces on top of the lower
level :mod:`thread` module. level :mod:`_thread` module. See also the :mod:`queue` module.
See also the :mod:`queue` module.
The :mod:`dummy_threading` module is provided for situations where The :mod:`dummy_threading` module is provided for situations where
:mod:`threading` cannot be used because :mod:`thread` is missing. :mod:`threading` cannot be used because :mod:`_thread` is missing.
This module defines the following functions and objects: This module defines the following functions and objects:
...@@ -170,7 +169,7 @@ Lock Objects ...@@ -170,7 +169,7 @@ Lock Objects
A primitive lock is a synchronization primitive that is not owned by a A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked. In Python, it is currently the lowest level particular thread when locked. In Python, it is currently the lowest level
synchronization primitive available, implemented directly by the :mod:`thread` synchronization primitive available, implemented directly by the :mod:`_thread`
extension module. extension module.
A primitive lock is in one of two states, "locked" or "unlocked". It is created A primitive lock is in one of two states, "locked" or "unlocked". It is created
......
...@@ -120,7 +120,7 @@ PyAPI_DATA(int) _Py_CheckInterval; ...@@ -120,7 +120,7 @@ PyAPI_DATA(int) _Py_CheckInterval;
Py_END_ALLOW_THREADS!!! Py_END_ALLOW_THREADS!!!
The function PyEval_InitThreads() should be called only from The function PyEval_InitThreads() should be called only from
initthread() in "threadmodule.c". init_thread() in "_threadmodule.c".
Note that not yet all candidates have been converted to use this Note that not yet all candidates have been converted to use this
mechanism! mechanism!
......
...@@ -6,9 +6,9 @@ not need to be rewritten for when the thread module is not present. ...@@ -6,9 +6,9 @@ not need to be rewritten for when the thread module is not present.
Suggested usage is:: Suggested usage is::
try: try:
import thread import _thread
except ImportError: except ImportError:
import dummy_thread as thread import _dummy_thread as _thread
""" """
# Exports only things specified by thread documentation; # Exports only things specified by thread documentation;
...@@ -20,17 +20,17 @@ import traceback as _traceback ...@@ -20,17 +20,17 @@ import traceback as _traceback
import warnings import warnings
class error(Exception): class error(Exception):
"""Dummy implementation of thread.error.""" """Dummy implementation of _thread.error."""
def __init__(self, *args): def __init__(self, *args):
self.args = args self.args = args
def start_new_thread(function, args, kwargs={}): def start_new_thread(function, args, kwargs={}):
"""Dummy implementation of thread.start_new_thread(). """Dummy implementation of _thread.start_new_thread().
Compatibility is maintained by making sure that ``args`` is a Compatibility is maintained by making sure that ``args`` is a
tuple and ``kwargs`` is a dictionary. If an exception is raised tuple and ``kwargs`` is a dictionary. If an exception is raised
and it is SystemExit (which can be done by thread.exit()) it is and it is SystemExit (which can be done by _thread.exit()) it is
caught and nothing is done; all other exceptions are printed out caught and nothing is done; all other exceptions are printed out
by using traceback.print_exc(). by using traceback.print_exc().
...@@ -57,34 +57,34 @@ def start_new_thread(function, args, kwargs={}): ...@@ -57,34 +57,34 @@ def start_new_thread(function, args, kwargs={}):
raise KeyboardInterrupt raise KeyboardInterrupt
def exit(): def exit():
"""Dummy implementation of thread.exit().""" """Dummy implementation of _thread.exit()."""
raise SystemExit raise SystemExit
def get_ident(): def get_ident():
"""Dummy implementation of thread.get_ident(). """Dummy implementation of _thread.get_ident().
Since this module should only be used when threadmodule is not Since this module should only be used when _threadmodule is not
available, it is safe to assume that the current process is the available, it is safe to assume that the current process is the
only thread. Thus a constant can be safely returned. only thread. Thus a constant can be safely returned.
""" """
return -1 return -1
def allocate_lock(): def allocate_lock():
"""Dummy implementation of thread.allocate_lock().""" """Dummy implementation of _thread.allocate_lock()."""
return LockType() return LockType()
def stack_size(size=None): def stack_size(size=None):
"""Dummy implementation of thread.stack_size().""" """Dummy implementation of _thread.stack_size()."""
if size is not None: if size is not None:
raise error("setting thread stack size not supported") raise error("setting thread stack size not supported")
return 0 return 0
class LockType(object): class LockType(object):
"""Class implementing dummy implementation of thread.LockType. """Class implementing dummy implementation of _thread.LockType.
Compatibility is maintained by maintaining self.locked_status Compatibility is maintained by maintaining self.locked_status
which is a boolean that stores the state of the lock. Pickling of which is a boolean that stores the state of the lock. Pickling of
the lock, though, should not be done since if the thread module is the lock, though, should not be done since if the _thread module is
then used with an unpickled ``lock()`` from here problems could then used with an unpickled ``lock()`` from here problems could
occur from this class not having atomic methods. occur from this class not having atomic methods.
......
...@@ -18,9 +18,9 @@ from re import IGNORECASE ...@@ -18,9 +18,9 @@ from re import IGNORECASE
from re import escape as re_escape from re import escape as re_escape
from datetime import date as datetime_date from datetime import date as datetime_date
try: try:
from thread import allocate_lock as _thread_allocate_lock from _thread import allocate_lock as _thread_allocate_lock
except: except:
from dummy_thread import allocate_lock as _thread_allocate_lock from _dummy_thread import allocate_lock as _thread_allocate_lock
__all__ = [] __all__ = []
......
...@@ -526,8 +526,8 @@ def _checkflag(flag, file): ...@@ -526,8 +526,8 @@ def _checkflag(flag, file):
# BerkeleyDB was too. # BerkeleyDB was too.
try: try:
import thread import _thread
del thread del _thread
if db.version() < (3, 3, 0): if db.version() < (3, 3, 0):
db.DB_THREAD = 0 db.DB_THREAD = 0
except ImportError: except ImportError:
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
The module ``_dummy_threading`` is added to ``sys.modules`` in order The module ``_dummy_threading`` is added to ``sys.modules`` in order
to not have ``threading`` considered imported. Had ``threading`` been to not have ``threading`` considered imported. Had ``threading`` been
directly imported it would have made all subsequent imports succeed directly imported it would have made all subsequent imports succeed
regardless of whether ``thread`` was available which is not desired. regardless of whether ``_thread`` was available which is not desired.
""" """
from sys import modules as sys_modules from sys import modules as sys_modules
import dummy_thread import _dummy_thread
# Declaring now so as to not have to nest ``try``s to get proper clean-up. # Declaring now so as to not have to nest ``try``s to get proper clean-up.
holding_thread = False holding_thread = False
...@@ -16,15 +16,15 @@ holding_threading = False ...@@ -16,15 +16,15 @@ holding_threading = False
holding__threading_local = False holding__threading_local = False
try: try:
# Could have checked if ``thread`` was not in sys.modules and gone # Could have checked if ``_thread`` was not in sys.modules and gone
# a different route, but decided to mirror technique used with # a different route, but decided to mirror technique used with
# ``threading`` below. # ``threading`` below.
if 'thread' in sys_modules: if '_thread' in sys_modules:
held_thread = sys_modules['thread'] held_thread = sys_modules['_thread']
holding_thread = True holding_thread = True
# Must have some module named ``thread`` that implements its API # Must have some module named ``_thread`` that implements its API
# in order to initially import ``threading``. # in order to initially import ``threading``.
sys_modules['thread'] = sys_modules['dummy_thread'] sys_modules['_thread'] = sys_modules['_dummy_thread']
if 'threading' in sys_modules: if 'threading' in sys_modules:
# If ``threading`` is already imported, might as well prevent # If ``threading`` is already imported, might as well prevent
...@@ -68,11 +68,11 @@ finally: ...@@ -68,11 +68,11 @@ finally:
# Put back ``thread`` if we overwrote, else del the entry we made # Put back ``thread`` if we overwrote, else del the entry we made
if holding_thread: if holding_thread:
sys_modules['thread'] = held_thread sys_modules['_thread'] = held_thread
del held_thread del held_thread
else: else:
del sys_modules['thread'] del sys_modules['_thread']
del holding_thread del holding_thread
del dummy_thread del _dummy_thread
del sys_modules del sys_modules
...@@ -3,7 +3,7 @@ import linecache ...@@ -3,7 +3,7 @@ import linecache
import time import time
import socket import socket
import traceback import traceback
import thread import _thread as thread
import threading import threading
import queue import queue
......
...@@ -35,7 +35,7 @@ except ImportError: ...@@ -35,7 +35,7 @@ except ImportError:
codecs = None codecs = None
try: try:
import thread import _thread as thread
import threading import threading
except ImportError: except ImportError:
thread = None thread = None
......
...@@ -27,7 +27,7 @@ To use, simply 'import logging' and log away! ...@@ -27,7 +27,7 @@ To use, simply 'import logging' and log away!
import sys, logging, logging.handlers, socket, struct, os, traceback import sys, logging, logging.handlers, socket, struct, os, traceback
try: try:
import thread import _thread as thread
import threading import threading
except ImportError: except ImportError:
thread = None thread = None
......
...@@ -96,11 +96,11 @@ class Message(rfc822.Message): ...@@ -96,11 +96,11 @@ class Message(rfc822.Message):
# ----------------- # -----------------
try: try:
import thread import _thread
except ImportError: except ImportError:
import dummy_thread as thread import _dummy_thread as _thread
_counter_lock = thread.allocate_lock() _counter_lock = _thread.allocate_lock()
del thread del _thread
_counter = 0 _counter = 0
def _get_next_counter(): def _get_next_counter():
......
...@@ -347,7 +347,7 @@ class Doc: ...@@ -347,7 +347,7 @@ class Doc:
if (isinstance(object, type(os)) and if (isinstance(object, type(os)) and
(object.__name__ in ('errno', 'exceptions', 'gc', 'imp', (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
'marshal', 'posix', 'signal', 'sys', 'marshal', 'posix', 'signal', 'sys',
'thread', 'zipimport') or '_thread', 'zipimport') or
(file.startswith(basedir) and (file.startswith(basedir) and
not file.startswith(os.path.join(basedir, 'site-packages'))))): not file.startswith(os.path.join(basedir, 'site-packages'))))):
if docloc.startswith("http://"): if docloc.startswith("http://"):
......
...@@ -548,8 +548,8 @@ class Telnet: ...@@ -548,8 +548,8 @@ class Telnet:
def mt_interact(self): def mt_interact(self):
"""Multithreaded version of interact().""" """Multithreaded version of interact()."""
import thread import _thread
thread.start_new_thread(self.listener, ()) _thread.start_new_thread(self.listener, ())
while 1: while 1:
line = sys.stdin.readline() line = sys.stdin.readline()
if not line: if not line:
......
...@@ -52,9 +52,9 @@ else: ...@@ -52,9 +52,9 @@ else:
try: try:
import thread as _thread import _thread
except ImportError: except ImportError:
import dummy_thread as _thread import _dummy_thread as _thread
_allocate_lock = _thread.allocate_lock _allocate_lock = _thread.allocate_lock
_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
......
...@@ -6,9 +6,9 @@ ...@@ -6,9 +6,9 @@
# http://bugs.python.org/issue595601 # http://bugs.python.org/issue595601
# http://bugs.python.org/issue815646 # http://bugs.python.org/issue815646
import thread import _thread
while 1: while 1:
f = open("multithreaded_close.tmp", "w") f = open("multithreaded_close.tmp", "w")
thread.start_new_thread(f.close, ()) _thread.start_new_thread(f.close, ())
f.close() f.close()
...@@ -9,7 +9,7 @@ On some systems (e.g. Solaris without posix threads) we find that all ...@@ -9,7 +9,7 @@ On some systems (e.g. Solaris without posix threads) we find that all
active threads survive in the child after a fork(); this is an error. active threads survive in the child after a fork(); this is an error.
""" """
import os, sys, time, thread, unittest import os, sys, time, _thread, unittest
LONGSLEEP = 2 LONGSLEEP = 2
SHORTSLEEP = 0.5 SHORTSLEEP = 0.5
...@@ -43,7 +43,7 @@ class ForkWait(unittest.TestCase): ...@@ -43,7 +43,7 @@ class ForkWait(unittest.TestCase):
def test_wait(self): def test_wait(self):
for i in range(NUM_THREADS): for i in range(NUM_THREADS):
thread.start_new(self.f, (i,)) _thread.start_new(self.f, (i,))
time.sleep(LONGSLEEP) time.sleep(LONGSLEEP)
......
...@@ -63,7 +63,7 @@ class AllTest(unittest.TestCase): ...@@ -63,7 +63,7 @@ class AllTest(unittest.TestCase):
self.check_all("dircache") self.check_all("dircache")
self.check_all("dis") self.check_all("dis")
self.check_all("doctest") self.check_all("doctest")
self.check_all("dummy_thread") self.check_all("_dummy_thread")
self.check_all("dummy_threading") self.check_all("dummy_threading")
self.check_all("filecmp") self.check_all("filecmp")
self.check_all("fileinput") self.check_all("fileinput")
......
# test asynchat -- requires threading # test asynchat -- requires threading
import thread # If this fails, we can't test this module import _thread as thread # If this fails, we can't test this module
import asyncore, asynchat, socket, threading, time import asyncore, asynchat, socket, threading, time
import unittest import unittest
import sys import sys
......
...@@ -22,13 +22,13 @@ def test_main(): ...@@ -22,13 +22,13 @@ def test_main():
idents = [] idents = []
def callback(): def callback():
idents.append(thread.get_ident()) idents.append(_thread.get_ident())
_testcapi._test_thread_state(callback) _testcapi._test_thread_state(callback)
a = b = callback a = b = callback
time.sleep(1) time.sleep(1)
# Check our main thread is in the list exactly 3 times. # Check our main thread is in the list exactly 3 times.
if idents.count(thread.get_ident()) != 3: if idents.count(_thread.get_ident()) != 3:
raise support.TestFailed( raise support.TestFailed(
"Couldn't find main thread correctly in the list") "Couldn't find main thread correctly in the list")
...@@ -39,11 +39,11 @@ def test_main(): ...@@ -39,11 +39,11 @@ def test_main():
have_thread_state = False have_thread_state = False
if have_thread_state: if have_thread_state:
import thread import _thread
import time import time
TestThreadState() TestThreadState()
import threading import threading
t=threading.Thread(target=TestThreadState) t = threading.Thread(target=TestThreadState)
t.start() t.start()
t.join() t.join()
......
...@@ -5,15 +5,15 @@ to be used, test_main() can be called with the module to use as the thread ...@@ -5,15 +5,15 @@ to be used, test_main() can be called with the module to use as the thread
implementation as its sole argument. implementation as its sole argument.
""" """
import dummy_thread as _thread import _dummy_thread as _thread
import time import time
import queue import queue
import random import random
import unittest import unittest
from test import support from test import support
DELAY = 0 # Set > 0 when testing a module other than dummy_thread, such as DELAY = 0 # Set > 0 when testing a module other than _dummy_thread, such as
# the 'thread' module. # the '_thread' module.
class LockTests(unittest.TestCase): class LockTests(unittest.TestCase):
"""Test lock objects.""" """Test lock objects."""
......
...@@ -6,7 +6,8 @@ from test import support ...@@ -6,7 +6,8 @@ from test import support
import errno import errno
import socket import socket
import select import select
import thread, threading import _thread as thread
import threading
import time import time
import traceback import traceback
import queue import queue
......
...@@ -191,7 +191,7 @@ class SysModuleTest(unittest.TestCase): ...@@ -191,7 +191,7 @@ class SysModuleTest(unittest.TestCase):
def test_current_frames(self): def test_current_frames(self):
have_threads = True have_threads = True
try: try:
import thread import _thread
except ImportError: except ImportError:
have_threads = False have_threads = False
...@@ -202,7 +202,7 @@ class SysModuleTest(unittest.TestCase): ...@@ -202,7 +202,7 @@ class SysModuleTest(unittest.TestCase):
# Test sys._current_frames() in a WITH_THREADS build. # Test sys._current_frames() in a WITH_THREADS build.
def current_frames_with_threads(self): def current_frames_with_threads(self):
import threading, thread import threading, _thread
import traceback import traceback
# Spawn a thread that blocks at a known place. Then the main # Spawn a thread that blocks at a known place. Then the main
...@@ -216,7 +216,7 @@ class SysModuleTest(unittest.TestCase): ...@@ -216,7 +216,7 @@ class SysModuleTest(unittest.TestCase):
g456() g456()
def g456(): def g456():
thread_info.append(thread.get_ident()) thread_info.append(_thread.get_ident())
entered_g.set() entered_g.set()
leave_g.wait() leave_g.wait()
...@@ -232,7 +232,7 @@ class SysModuleTest(unittest.TestCase): ...@@ -232,7 +232,7 @@ class SysModuleTest(unittest.TestCase):
d = sys._current_frames() d = sys._current_frames()
main_id = thread.get_ident() main_id = _thread.get_ident()
self.assert_(main_id in d) self.assert_(main_id in d)
self.assert_(thread_id in d) self.assert_(thread_id in d)
......
...@@ -2,7 +2,7 @@ import os ...@@ -2,7 +2,7 @@ import os
import unittest import unittest
import random import random
from test import support from test import support
import thread import _thread as thread
import time import time
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
# complains several times about module random having no attribute # complains several times about module random having no attribute
# randrange, and then Python hangs. # randrange, and then Python hangs.
import thread import _thread as thread
from test.support import verbose, TestSkipped, TestFailed from test.support import verbose, TestSkipped, TestFailed
critical_section = thread.allocate_lock() critical_section = thread.allocate_lock()
......
...@@ -16,7 +16,7 @@ provoking a 2.0 failure under Linux. ...@@ -16,7 +16,7 @@ provoking a 2.0 failure under Linux.
NUM_THREADS = 20 NUM_THREADS = 20
FILES_PER_THREAD = 50 FILES_PER_THREAD = 50
import thread # If this fails, we can't test this module import _thread as thread # If this fails, we can't test this module
import threading import threading
import tempfile import tempfile
......
...@@ -5,7 +5,7 @@ from test.support import verbose ...@@ -5,7 +5,7 @@ from test.support import verbose
import random import random
import sys import sys
import threading import threading
import thread import _thread
import time import time
import unittest import unittest
import weakref import weakref
...@@ -88,7 +88,7 @@ class ThreadTests(unittest.TestCase): ...@@ -88,7 +88,7 @@ class ThreadTests(unittest.TestCase):
print('with 256kB thread stack size...') print('with 256kB thread stack size...')
try: try:
threading.stack_size(262144) threading.stack_size(262144)
except thread.error: except _thread.error:
if verbose: if verbose:
print('platform does not support changing thread stack size') print('platform does not support changing thread stack size')
return return
...@@ -101,7 +101,7 @@ class ThreadTests(unittest.TestCase): ...@@ -101,7 +101,7 @@ class ThreadTests(unittest.TestCase):
print('with 1MB thread stack size...') print('with 1MB thread stack size...')
try: try:
threading.stack_size(0x100000) threading.stack_size(0x100000)
except thread.error: except _thread.error:
if verbose: if verbose:
print('platform does not support changing thread stack size') print('platform does not support changing thread stack size')
return return
...@@ -120,7 +120,7 @@ class ThreadTests(unittest.TestCase): ...@@ -120,7 +120,7 @@ class ThreadTests(unittest.TestCase):
mutex = threading.Lock() mutex = threading.Lock()
mutex.acquire() mutex.acquire()
tid = thread.start_new_thread(f, (mutex,)) tid = _thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish. # Wait for the thread to finish.
mutex.acquire() mutex.acquire()
self.assert_(tid in threading._active) self.assert_(tid in threading._active)
...@@ -154,7 +154,7 @@ class ThreadTests(unittest.TestCase): ...@@ -154,7 +154,7 @@ class ThreadTests(unittest.TestCase):
class Worker(threading.Thread): class Worker(threading.Thread):
def run(self): def run(self):
self.id = thread.get_ident() self.id = _thread.get_ident()
self.finished = False self.finished = False
try: try:
...@@ -211,10 +211,10 @@ class ThreadTests(unittest.TestCase): ...@@ -211,10 +211,10 @@ class ThreadTests(unittest.TestCase):
import subprocess import subprocess
rc = subprocess.call([sys.executable, "-c", """if 1: rc = subprocess.call([sys.executable, "-c", """if 1:
import ctypes, sys, time, thread import ctypes, sys, time, _thread
# This lock is used as a simple event variable. # This lock is used as a simple event variable.
ready = thread.allocate_lock() ready = _thread.allocate_lock()
ready.acquire() ready.acquire()
# Module globals are cleared before __del__ is run # Module globals are cleared before __del__ is run
...@@ -231,7 +231,7 @@ class ThreadTests(unittest.TestCase): ...@@ -231,7 +231,7 @@ class ThreadTests(unittest.TestCase):
ready.release() ready.release()
time.sleep(100) time.sleep(100)
thread.start_new_thread(waitingThread, ()) _thread.start_new_thread(waitingThread, ())
ready.acquire() # Be sure the other thread is waiting. ready.acquire() # Be sure the other thread is waiting.
sys.exit(42) sys.exit(42)
"""]) """])
...@@ -357,7 +357,7 @@ class ThreadingExceptionTests(unittest.TestCase): ...@@ -357,7 +357,7 @@ class ThreadingExceptionTests(unittest.TestCase):
def test_main(): def test_main():
test.support.run_unittest(ThreadTests, test.support.run_unittest(ThreadTests,
ThreadingExceptionTests) ThreadingExceptionTests)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()
"""PyUnit testing that threads honor our signal semantics""" """PyUnit testing that threads honor our signal semantics"""
import unittest import unittest
import thread import _thread as thread
import signal import signal
import os import os
import sys import sys
......
"""Thread module emulating a subset of Java's threading model.""" """Thread module emulating a subset of Java's threading model."""
import sys as _sys import sys as _sys
import _thread
try:
import thread
except ImportError:
del _sys.modules[__name__]
raise
from time import time as _time, sleep as _sleep from time import time as _time, sleep as _sleep
from traceback import format_exc as _format_exc from traceback import format_exc as _format_exc
...@@ -17,11 +12,11 @@ __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', ...@@ -17,11 +12,11 @@ __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
'Timer', 'setprofile', 'settrace', 'local', 'stack_size'] 'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
_start_new_thread = thread.start_new_thread _start_new_thread = _thread.start_new_thread
_allocate_lock = thread.allocate_lock _allocate_lock = _thread.allocate_lock
_get_ident = thread.get_ident _get_ident = _thread.get_ident
ThreadError = thread.error ThreadError = _thread.error
del thread del _thread
# Debug support (adapted from ihooks.py). # Debug support (adapted from ihooks.py).
...@@ -556,18 +551,18 @@ class Thread(_Verbose): ...@@ -556,18 +551,18 @@ class Thread(_Verbose):
def _delete(self): def _delete(self):
"Remove current thread from the dict of currently running threads." "Remove current thread from the dict of currently running threads."
# Notes about running with dummy_thread: # Notes about running with _dummy_thread:
# #
# Must take care to not raise an exception if dummy_thread is being # Must take care to not raise an exception if _dummy_thread is being
# used (and thus this module is being used as an instance of # used (and thus this module is being used as an instance of
# dummy_threading). dummy_thread.get_ident() always returns -1 since # dummy_threading). _dummy_thread.get_ident() always returns -1 since
# there is only one thread if dummy_thread is being used. Thus # there is only one thread if _dummy_thread is being used. Thus
# len(_active) is always <= 1 here, and any Thread instance created # len(_active) is always <= 1 here, and any Thread instance created
# overwrites the (if any) thread currently registered in _active. # overwrites the (if any) thread currently registered in _active.
# #
# An instance of _MainThread is always created by 'threading'. This # An instance of _MainThread is always created by 'threading'. This
# gets overwritten the instant an instance of Thread is created; both # gets overwritten the instant an instance of Thread is created; both
# threads return -1 from dummy_thread.get_ident() and thus have the # threads return -1 from _dummy_thread.get_ident() and thus have the
# same key in the dict. So when the _MainThread instance created by # same key in the dict. So when the _MainThread instance created by
# 'threading' tries to clean itself up when atexit calls this method # 'threading' tries to clean itself up when atexit calls this method
# it gets a KeyError if another Thread instance was created. # it gets a KeyError if another Thread instance was created.
...@@ -763,7 +758,7 @@ def enumerate(): ...@@ -763,7 +758,7 @@ def enumerate():
_active_limbo_lock.release() _active_limbo_lock.release()
return active return active
from thread import stack_size from _thread import stack_size
# Create the main thread object, # Create the main thread object,
# and make it available for the interpreter # and make it available for the interpreter
...@@ -775,7 +770,7 @@ _shutdown = _MainThread()._exitfunc ...@@ -775,7 +770,7 @@ _shutdown = _MainThread()._exitfunc
# module, or from the python fallback # module, or from the python fallback
try: try:
from thread import _local as local from _thread import _local as local
except ImportError: except ImportError:
from _threading_local import local from _threading_local import local
......
...@@ -1988,8 +1988,8 @@ zipfile Read & write PK zipped files. ...@@ -1988,8 +1988,8 @@ zipfile Read & write PK zipped files.
re Functions useful for working with regular expressions re Functions useful for working with regular expressions
string Useful string and characters functions and exceptions string Useful string and characters functions and exceptions
random Mersenne Twister pseudo-random number generator random Mersenne Twister pseudo-random number generator
thread Low-level primitives for working with process threads _thread Low-level primitives for working with process threads
threading idem, new recommanded interface. threading idem, new recommended interface.
* Unix/Posix * * Unix/Posix *
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
# based on configure-time options. # based on configure-time options.
# Threading # Threading
@USE_THREAD_MODULE@thread threadmodule.c @USE_THREAD_MODULE@_thread _threadmodule.c
# The signal module # The signal module
@USE_SIGNAL_MODULE@signal signalmodule.c @USE_SIGNAL_MODULE@signal signalmodule.c
......
...@@ -688,7 +688,7 @@ unlock it. A thread attempting to lock a lock that it has already locked\n\ ...@@ -688,7 +688,7 @@ unlock it. A thread attempting to lock a lock that it has already locked\n\
will block until another thread unlocks it. Deadlocks may ensue."); will block until another thread unlocks it. Deadlocks may ensue.");
PyMODINIT_FUNC PyMODINIT_FUNC
initthread(void) init_thread(void)
{ {
PyObject *m, *d; PyObject *m, *d;
...@@ -699,13 +699,13 @@ initthread(void) ...@@ -699,13 +699,13 @@ initthread(void)
return; return;
/* Create the module and add the functions */ /* Create the module and add the functions */
m = Py_InitModule3("thread", thread_methods, thread_doc); m = Py_InitModule3("_thread", thread_methods, thread_doc);
if (m == NULL) if (m == NULL)
return; return;
/* Add a symbolic constant */ /* Add a symbolic constant */
d = PyModule_GetDict(m); d = PyModule_GetDict(m);
ThreadError = PyErr_NewException("thread.error", NULL, NULL); ThreadError = PyErr_NewException("_thread.error", NULL, NULL);
PyDict_SetItemString(d, "error", ThreadError); PyDict_SetItemString(d, "error", ThreadError);
Locktype.tp_doc = lock_doc; Locktype.tp_doc = lock_doc;
Py_INCREF(&Locktype); Py_INCREF(&Locktype);
......
...@@ -679,7 +679,7 @@ SOURCE=..\..\Python\thread.c ...@@ -679,7 +679,7 @@ SOURCE=..\..\Python\thread.c
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=..\..\Modules\threadmodule.c SOURCE=..\..\Modules\_threadmodule.c
# End Source File # End Source File
# Begin Source File # Begin Source File
......
...@@ -768,7 +768,7 @@ ...@@ -768,7 +768,7 @@
RelativePath="..\..\Python\thread.c"> RelativePath="..\..\Python\thread.c">
</File> </File>
<File <File
RelativePath="..\..\Modules\threadmodule.c"> RelativePath="..\..\Modules\_threadmodule.c">
</File> </File>
<File <File
RelativePath="..\..\Modules\timemodule.c"> RelativePath="..\..\Modules\timemodule.c">
......
...@@ -1127,7 +1127,7 @@ ...@@ -1127,7 +1127,7 @@
> >
</File> </File>
<File <File
RelativePath="..\..\Modules\threadmodule.c" RelativePath="..\..\Modules\_threadmodule.c"
> >
</File> </File>
<File <File
......
...@@ -22,7 +22,7 @@ extern void init_sha1(void); ...@@ -22,7 +22,7 @@ extern void init_sha1(void);
extern void init_sha256(void); extern void init_sha256(void);
extern void init_sha512(void); extern void init_sha512(void);
extern void inittime(void); extern void inittime(void);
extern void initthread(void); extern void init_thread(void);
extern void initcStringIO(void); extern void initcStringIO(void);
#ifdef WIN32 #ifdef WIN32
extern void initmsvcrt(void); extern void initmsvcrt(void);
...@@ -93,7 +93,7 @@ struct _inittab _PyImport_Inittab[] = { ...@@ -93,7 +93,7 @@ struct _inittab _PyImport_Inittab[] = {
{"_sha512", init_sha512}, {"_sha512", init_sha512},
{"time", inittime}, {"time", inittime},
#ifdef WITH_THREAD #ifdef WITH_THREAD
{"thread", initthread}, {"_thread", init_thread},
#endif #endif
{"cStringIO", initcStringIO}, {"cStringIO", initcStringIO},
#ifdef WIN32 #ifdef WIN32
......
...@@ -281,7 +281,7 @@ SRC.MODULES= $(addprefix $(TOP), \ ...@@ -281,7 +281,7 @@ SRC.MODULES= $(addprefix $(TOP), \
Modules/gcmodule.c \ Modules/gcmodule.c \
Modules/signalmodule.c \ Modules/signalmodule.c \
Modules/posixmodule.c \ Modules/posixmodule.c \
Modules/threadmodule.c \ Modules/_threadmodule.c \
Modules/arraymodule.c \ Modules/arraymodule.c \
Modules/binascii.c \ Modules/binascii.c \
Modules/cmathmodule.c \ Modules/cmathmodule.c \
......
...@@ -39,7 +39,7 @@ PERFORMANCE OF THIS SOFTWARE. ...@@ -39,7 +39,7 @@ PERFORMANCE OF THIS SOFTWARE.
extern void initos2(); extern void initos2();
extern void initsignal(); extern void initsignal();
#ifdef WITH_THREAD #ifdef WITH_THREAD
extern void initthread(); extern void init_thread();
#endif #endif
extern void init_codecs(); extern void init_codecs();
extern void init_csv(); extern void init_csv();
...@@ -99,7 +99,7 @@ struct _inittab _PyImport_Inittab[] = { ...@@ -99,7 +99,7 @@ struct _inittab _PyImport_Inittab[] = {
{"os2", initos2}, {"os2", initos2},
{"signal", initsignal}, {"signal", initsignal},
#ifdef WITH_THREAD #ifdef WITH_THREAD
{"thread", initthread}, {"_thread", init_thread},
#endif #endif
{"_codecs", init_codecs}, {"_codecs", init_codecs},
{"_csv", init_csv}, {"_csv", init_csv},
......
...@@ -1194,8 +1194,8 @@ EXPORTS ...@@ -1194,8 +1194,8 @@ EXPORTS
; From python26_s.lib(posixmodule) ; From python26_s.lib(posixmodule)
; "initos2" ; "initos2"
; From python26_s.lib(threadmodule) ; From python26_s.lib(_threadmodule)
; "initthread" ; "init_thread"
; From python26_s.lib(arraymodule) ; From python26_s.lib(arraymodule)
; "initarray" ; "initarray"
......
...@@ -33,7 +33,7 @@ extern void initselect(void); ...@@ -33,7 +33,7 @@ extern void initselect(void);
extern void init_socket(void); extern void init_socket(void);
extern void initstruct(void); extern void initstruct(void);
extern void inittime(void); extern void inittime(void);
extern void initthread(void); extern void init_thread(void);
extern void initcStringIO(void); extern void initcStringIO(void);
extern void initpcre(void); extern void initpcre(void);
#ifdef WIN32 #ifdef WIN32
...@@ -76,7 +76,7 @@ struct _inittab _PyImport_Inittab[] = { ...@@ -76,7 +76,7 @@ struct _inittab _PyImport_Inittab[] = {
{"struct", initstruct}, {"struct", initstruct},
{"time", inittime}, {"time", inittime},
#ifdef WITH_THREAD #ifdef WITH_THREAD
{"thread", initthread}, {"_thread", init_thread},
#endif #endif
{"cStringIO", initcStringIO}, {"cStringIO", initcStringIO},
{"pcre", initpcre}, {"pcre", initpcre},
......
...@@ -868,7 +868,7 @@ termios.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classo ...@@ -868,7 +868,7 @@ termios.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h $(PY_INCLUDE)\classo
$(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \ $(PY_INCLUDE)\sliceobject.h $(PY_INCLUDE)\stringobject.h \
$(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h $(PY_INCLUDE)\sysmodule.h $(PY_INCLUDE)\traceback.h $(PY_INCLUDE)\tupleobject.h
threadmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \ _threadmodule.obj: $(PY_INCLUDE)\abstract.h $(PY_INCLUDE)\ceval.h \
$(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \ $(PY_INCLUDE)\classobject.h $(PY_INCLUDE)\cobject.h $(PY_INCLUDE)\complexobject.h \
pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \ pyconfig.h $(PY_INCLUDE)\dictobject.h $(PY_INCLUDE)\fileobject.h \
$(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \ $(PY_INCLUDE)\floatobject.h $(PY_INCLUDE)\funcobject.h $(PY_INCLUDE)\import.h \
......
...@@ -630,7 +630,7 @@ termios.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \ ...@@ -630,7 +630,7 @@ termios.obj: abstract.h ceval.h classobject.h cobject.h complexobject.h \
pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \ pythonrun.h rangeobject.h sliceobject.h stringobject.h sysmodule.h \
traceback.h tupleobject.h traceback.h tupleobject.h
threadmodule.obj: abstract.h ceval.h classobject.h cobject.h \ _threadmodule.obj: abstract.h ceval.h classobject.h cobject.h \
complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \ complexobject.h pyconfig.h dictobject.h fileobject.h floatobject.h \
funcobject.h import.h intobject.h intrcheck.h listobject.h \ funcobject.h import.h intobject.h intrcheck.h listobject.h \
longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \ longobject.h methodobject.h modsupport.h moduleobject.h mymalloc.h \
......
...@@ -1131,7 +1131,7 @@ ...@@ -1131,7 +1131,7 @@
> >
</File> </File>
<File <File
RelativePath="..\Modules\threadmodule.c" RelativePath="..\Modules\_threadmodule.c"
> >
</File> </File>
<File <File
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment