Example #1
0
def test():
    global TID, tid, io, wh, randint, alive
    import random
    randint = random.randint

    TID = 0                             # thread ID (1, 2, ...)
    tid = thread.allocate_lock()        # for changing TID
    io  = thread.allocate_lock()        # for printing, and 'alive'
    wh  = thread.allocate_lock()        # for calls to random
    alive = []                          # IDs of active threads

    NSORTS = 5
    arrays = []
    for i in range(NSORTS):
        arrays.append( range( (i+1)*10 ) )

    bar = barrier(NSORTS)
    finished = event()
    for i in range(NSORTS):
        _new_thread(_run_one_sort, arrays[i], bar, finished)
    finished.wait()

    print('all threads done, and checking results ...')
    if alive:
        raise ValueError('threads still alive at end', alive)
    for i in range(NSORTS):
        a = arrays[i]
        if len(a) != (i+1)*10:
            raise ValueError('length of array', i, 'screwed up')
        _check_sort(a)

    print('test passed!', TID, 'threads created in all')
Example #2
0
    def test_current_frames(self):
        import sys
        import time
        import _thread

        # XXX workaround for now: to prevent deadlocks, call
        # sys._current_frames() once before starting threads.
        # This is an issue in non-translated versions only.
        sys._current_frames()

        thread_id = _thread.get_ident()
        def other_thread():
            #print("thread started")
            lock2.release()
            lock1.acquire()
        lock1 = _thread.allocate_lock()
        lock2 = _thread.allocate_lock()
        lock1.acquire()
        lock2.acquire()
        _thread.start_new_thread(other_thread, ())

        def f():
            lock2.acquire()
            return sys._current_frames()

        frames = f()
        lock1.release()
        thisframe = frames.pop(thread_id)
        assert thisframe.f_code.co_name in ('f', '?')

        assert len(frames) == 1
        _, other_frame = frames.popitem()
        assert other_frame.f_code.co_name in ('other_thread', '?')
Example #3
0
 def test_tstate_lock(self):
     # Test an implementation detail of Thread objects.
     started = _thread.allocate_lock()
     finish = _thread.allocate_lock()
     started.acquire()
     finish.acquire()
     def f():
         started.release()
         finish.acquire()
         time.sleep(0.01)
     # The tstate lock is None until the thread is started
     t = threading.Thread(target=f)
     self.assertIs(t._tstate_lock, None)
     t.start()
     started.acquire()
     self.assertTrue(t.is_alive())
     # The tstate lock can't be acquired when the thread is running
     # (or suspended).
     tstate_lock = t._tstate_lock
     self.assertFalse(tstate_lock.acquire(timeout=0), False)
     finish.release()
     # When the thread ends, the state_lock can be successfully
     # acquired.
     self.assertTrue(tstate_lock.acquire(timeout=5), False)
     # But is_alive() is still True:  we hold _tstate_lock now, which
     # prevents is_alive() from knowing the thread's end-of-life C code
     # is done.
     self.assertTrue(t.is_alive())
     # Let is_alive() find out the C code is done.
     tstate_lock.release()
     self.assertFalse(t.is_alive())
     # And verify the thread disposed of _tstate_lock.
     self.assertIsNone(t._tstate_lock)
     t.join()
Example #4
0
    def __init__(self):
        Gtk.IconView.__init__(self)
        self.set_item_width(BACKGROUND_ICONS_SIZE * 1.1)
        self._model = Gtk.ListStore(object, GdkPixbuf.Pixbuf, str, str)
        self._model_filter = self._model.filter_new()
        self._model_filter.set_visible_func(self.visible_func)
        self.set_model(self._model_filter)

        area = self.get_area()

        self.current_path = None

        pixbuf_renderer = Gtk.CellRendererPixbuf()
        text_renderer = Gtk.CellRendererText(ellipsize=Pango.EllipsizeMode.END)

        text_renderer.set_alignment(.5, .5)
        area.pack_start(pixbuf_renderer, True, False, False)
        area.pack_start(text_renderer, True, False, False)
        self.add_attribute(pixbuf_renderer, "pixbuf", 1)
        self.add_attribute(text_renderer, "markup", 2)
        text_renderer.set_property("alignment", Pango.Alignment.CENTER)

        self._loading_queue = []
        self._loading_queue_lock = thread.allocate_lock()

        self._loading_lock = thread.allocate_lock()
        self._loading = False

        self._loaded_data = []
        self._loaded_data_lock = thread.allocate_lock()
Example #5
0
 def test_repr_stopped(self):
     # Verify that "stopped" shows up in repr(Thread) appropriately.
     started = _thread.allocate_lock()
     finish = _thread.allocate_lock()
     started.acquire()
     finish.acquire()
     def f():
         started.release()
         finish.acquire()
     t = threading.Thread(target=f)
     t.start()
     started.acquire()
     self.assertIn("started", repr(t))
     finish.release()
     # "stopped" should appear in the repr in a reasonable amount of time.
     # Implementation detail:  as of this writing, that's trivially true
     # if .join() is called, and almost trivially true if .is_alive() is
     # called.  The detail we're testing here is that "stopped" shows up
     # "all on its own".
     LOOKING_FOR = "stopped"
     for i in range(500):
         if LOOKING_FOR in repr(t):
             break
         time.sleep(0.01)
     self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
     t.join()
Example #6
0
 def setUp(self):
     self.done_mutex = _thread.allocate_lock()
     self.done_mutex.acquire()
     self.running_mutex = _thread.allocate_lock()
     self.random_mutex = _thread.allocate_lock()
     self.created = 0
     self.running = 0
     self.next_ident = 0
 def __init__(self, func, args):
     self.getlock = thread.allocate_lock()
     self.putlock = thread.allocate_lock()
     self.getlock.acquire()
     self.putlock.acquire()
     self.func = func
     self.args = args
     self.done = 0
     self.killed = 0
     thread.start_new_thread(self._start, ())
Example #8
0
 def __init__(self, *pipes):
     self.active_pipes = set()
     self.active_sources = set()
     self.active_drains = set()
     self.active_sinks = set()
     self._add_pipes(*pipes)
     self.thread_lock = _thread.allocate_lock()
     self.command_lock = _thread.allocate_lock()
     self.__fdr,self.__fdw = os.pipe()
     self.threadid = None
Example #9
0
    def setUp(self):
        self.done_mutex = thread.allocate_lock()
        self.done_mutex.acquire()
        self.running_mutex = thread.allocate_lock()
        self.random_mutex = thread.allocate_lock()
        self.created = 0
        self.running = 0
        self.next_ident = 0

        key = support.threading_setup()
        self.addCleanup(support.threading_cleanup, *key)
Example #10
0
    def __init__(self, app):

        ToolbarPage.__init__(self, app, "Objects")

        self.namespaces = {}
        self.images = {}
        self.image_directions = {}
        self.selected_object = [None, None]
        self.is_active = False
        self.cur_rotation = 0
        x_adjust = 5
        pos = self.gui.getPosition()
        y_pos = pos.d_y
        x_pos = PyCEGUI.UDim(0, x_adjust)
        width = PyCEGUI.UDim(0.9, 0.0)
        label = self.gui.createChild("TaharezLook/Label",
                                     "ObjectsLabel")
        label.setText(_("Objects"))
        label.setWidth(width)
        label.setXPosition(x_pos)
        label.setProperty("HorzFormatting", "LeftAligned")
        items_panel = self.gui.createChild("TaharezLook/ScrollablePane",
                                           "Items_panel")
        y_pos.d_scale = y_pos.d_scale + 0.045
        items_panel.setXPosition(x_pos)
        items_panel.setYPosition(y_pos)
        size = self.gui.getSize()
        size.d_height.d_scale = size.d_height.d_scale - y_pos.d_scale
        size.d_width.d_offset = size.d_width.d_offset - x_adjust
        items_panel.setSize(size)
        self.items_panel = items_panel
        self.items = None
        self.have_objects_changed = False
        self.app.add_map_switch_callback(self.cb_map_changed)
        self.last_mouse_pos = None
        self.last_instance = None
        mode = self.app.current_mode
        mode.listener.add_callback("mouse_pressed",
                                   self.cb_map_clicked)
        mode.listener.add_callback("mouse_dragged",
                                   self.cb_map_clicked)
        mode.listener.add_callback("mouse_moved",
                                   self.cb_map_moved)
        mode.listener.add_callback("key_pressed",
                                   self.cb_key_pressed)
        self.app.add_project_clear_callback(self.cb_project_closed)
        self.app.add_objects_imported_callback(self.cb_objects_imported)
        self.objects = Queue()
        self.images_lock = _thread.allocate_lock()
        self.namespaces_lock = _thread.allocate_lock()
Example #11
0
    def __init__(self, directory):
        self.directory = directory
        self.peers = {}
        self.files = []
        self.filter_out_files = ('README.md', 'README.rst', 'LICENSE')

        # Threads (low level implementation)
        self.__run_init_threads = 0
        self.__run_init_thread_started = False
        self.__run_init_lock = allocate_lock()

        # More operating systems will be added soon.
        if os_type == 'Windows':
            files = glob.glob(self.directory + '\\*')
        elif os_type == 'Linux':
            files = glob.glob(self.directory + '/*')
        else:
            raise OSError('Your OS is not supported')

        for file in files:
            filename = ntpath.basename(file)
            if filename not in self.filter_out_files:
                self.files.append(filename)

        self.elements = len(self.files)
        # Todo: Remove none unicode chars from filenames ## Doh... not possile! do it later in peerobj. update.

        # Read all
        self.__read_all()
Example #12
0
	def __init__(self, server_address, RequestHandlerClass, maxthreads=100, pemfile=None, rest_handlers=None, userpass=None):
		try:
			if pemfile: #HTTPS server
				BaseServer.__init__(self, server_address, RequestHandlerClass)
				ctx = SSL.Context(SSL.SSLv23_METHOD)
				ctx.use_privatekey_file(pemfile)
				ctx.use_certificate_file(pemfile)
				self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
				self.server_bind()
				self.server_activate()
				self.httpstyle = "HTTPS"
			else: #HTTP server
				BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)
				self.httpstyle = "HTTP"
		except socket.error as e:
			if e.errno == 98:
				logging.log(logging.ERROR, "Cannot start HTTP server, address already in use")
				return
			else:
				raise
		self.lock = thread.allocate_lock()
		self.maxthreads = maxthreads
		self.threads = 0
		self.rest_handlers = rest_handlers
		self.userpass = userpass
Example #13
0
 def __init__(self, function, *args, **kwargs):
     "Initialize the Micrev_Timer object."
     self.__function = function
     self.__args = args
     self.__kwargs = kwargs
     self.__thread = False
     self.__lock = _thread.allocate_lock()
Example #14
0
		def __init__(self, classes, n_req):
			self.httpd = http.server.HTTPServer(("", 10080), self.RequestHandler)
			self.httpd.classes = classes
			self.httpd.assigs = set([c[0] for c in classes])
			self.lock_aturada = _thread.allocate_lock()
			self.lock_aturada.acquire()
			_thread.start_new_thread(self.serveix, (n_req,))
Example #15
0
 def __init__(self, func, args, kwargs):
     "Initializes instance from arguments and prepares to run."
     self.__func = func
     self.__args = args
     self.__kwargs = kwargs
     self.__mutex = _thread.allocate_lock()
     self.__mutex.acquire()
    def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp='pool.ntp.org', ntp_period=3600):
        self.id = id
        self.frequency = frequency
        self.datarate = datarate
        self.sf = self._dr_to_sf(datarate)
        self.ssid = ssid
        self.password = password
        self.server = server
        self.port = port
        self.ntp = ntp
        self.ntp_period = ntp_period

        self.rxnb = 0
        self.rxok = 0
        self.rxfw = 0
        self.dwnb = 0
        self.txnb = 0

        self.stat_alarm = None
        self.pull_alarm = None
        self.uplink_alarm = None

        self.udp_lock = _thread.allocate_lock()

        self.lora = None
        self.lora_sock = None
Example #17
0
    def test_many_threads(self):
        import _thread, time

        if self.can_start_many_threads:
            skip("this OS supports too many threads to check (> 1000)")
        lock = _thread.allocate_lock()
        lock.acquire()
        count = [0]

        def f():
            count[0] += 1
            lock.acquire()
            lock.release()
            count[0] -= 1

        try:
            try:
                for i in range(1000):
                    _thread.start_new_thread(f, ())
            finally:
                lock.release()
                # wait a bit to allow most threads to finish now
                while count[0] > 10:
                    print(count[0])  # <- releases the GIL
                print("ok.")
        except (_thread.error, MemoryError):
            pass
        else:
            raise Exception("could unexpectedly start 1000 threads")
        # safety: check that we can start a new thread here
        _thread.start_new_thread(lambda: None, ())
 def __init__ (self):
     r, w = self._fds = os.pipe()
     self.trigger = w
     asyncore.file_dispatcher.__init__(self, r)
     self.lock = _thread.allocate_lock()
     self.thunks = []
     self._closed = 0
Example #19
0
    def test__count(self):
        # Test the _count() function.
        orig = thread._count()
        mut = thread.allocate_lock()
        mut.acquire()
        started = []

        def task():
            started.append(None)
            mut.acquire()
            mut.release()

        with support.wait_threads_exit():
            thread.start_new_thread(task, ())
            while not started:
                time.sleep(POLL_SLEEP)
            self.assertEqual(thread._count(), orig + 1)
            # Allow the task to finish.
            mut.release()
            # The only reliable way to be sure that the thread ended from the
            # interpreter's point of view is to wait for the function object to be
            # destroyed.
            done = []
            wr = weakref.ref(task, lambda _: done.append(None))
            del task
            while not done:
                time.sleep(POLL_SLEEP)
            self.assertEqual(thread._count(), orig)
Example #20
0
 def test_lock_acquire_interruption(self):
     if self.using_pthread_cond:
         skip('POSIX condition variables cannot be interrupted')
     import _thread, signal, time
     # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
     # in a deadlock.
     # XXX this test can fail when the legacy (non-semaphore) implementation
     # of locks is used in thread_pthread.h, see issue #11223.
     oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
     try:
         lock = _thread.allocate_lock()
         lock.acquire()
         signal.alarm(1)
         t1 = time.time()
         # XXX: raises doesn't work here?
         #raises(KeyboardInterrupt, lock.acquire, timeout=5)
         try:
             lock.acquire(timeout=5)
         except KeyboardInterrupt:
             pass
         else:
             assert False, 'Expected KeyboardInterrupt'
         dt = time.time() - t1
         # Checking that KeyboardInterrupt was raised is not sufficient.
         # We want to assert that lock.acquire() was interrupted because
         # of the signal, not that the signal handler was called immediately
         # after timeout return of lock.acquire() (which can fool assertRaises).
         assert dt < 3.0
     finally:
         signal.signal(signal.SIGALRM, oldalrm)
Example #21
0
 def test_lock(self):
     import _thread
     lock = _thread.allocate_lock()
     assert type(lock) is _thread.LockType
     assert lock.locked() is False
     raises(_thread.error, lock.release)
     assert lock.locked() is False
     r = lock.acquire()
     assert r is True
     r = lock.acquire(False)
     assert r is False
     assert lock.locked() is True
     lock.release()
     assert lock.locked() is False
     raises(_thread.error, lock.release)
     assert lock.locked() is False
     feedback = []
     lock.acquire()
     def f():
         self.busywait(0.25)
         feedback.append(42)
         lock.release()
     assert lock.locked() is True
     _thread.start_new_thread(f, ())
     lock.acquire()
     assert lock.locked() is True
     assert feedback == [42]
Example #22
0
File: irc.py Project: bthate/meds
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._lock = _thread.allocate_lock()
     self._outqueue = queue.Queue()
     self._sock = None
     self._buffer = []
     self._lastline = ""
     self._error = ""
     self._status = "start"
     self.handlers = Object()
     self.type = self.__class__.__name__
     self.register("004", self.connected)
     self.register("ERROR", self.errored)
     self.register("366", self.h366)
     self.register("433", self.h433)
     self.register("513", self.h513)
     self.register("PING", self.pinged)
     self.register("PONG", self.ponged)
     self.register("QUIT", self.quited)
     self.register("INVITE", self.invited)
     self.register("PRIVMSG", self.privmsged)
     self.register("NOTICE", self.noticed)
     self.register("JOIN", self.joined)
     self.channels = []
     self.encoding = "utf-8"
     if "realname" not in self: self.realname = "meds"
     if "username" not in self: self.username = "******"
     if "server" not in self: self.server = "localhost"
     if "port" not in self: self.port = 6667
     if "nick" not in self: self.nick = "meds"
     if "channel" in self: self.channels.append(self.channel)
Example #23
0
    def __init__(self, ip, port, maxCn):
        '''(self, str, int, int) -> None

        Creates a new server instance.'''
        self.ip = ip
        self.port = port
        self.maxConnections = maxCn
        self.clients = {}
        self.channels = {}
        self.clientCount = 0
        self.lock = allocate_lock()
        try:            
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.bind((ip, port))
            self.sock.listen(self.maxConnections)         
            if self.sock:
                print('Woot! We established the socket on {0}:{1}'.format(self.ip ,self.port))
                #server loaded and is working. so self.running = True                
                self.running = True
        except:            
            if socket.error:            
                print('Socket Error while setting up server: {0}'.format(traceback.format_exc().splitlines()[-1]))
            else: print('Error while setting up server:\n{0}'.format(traceback.format_exc()))            
            #something has gone wrong, so self.running = False
            self.running = False
            return
Example #24
0
    def start(self, port=8080):
        """
        Starts the server. This will actually start the child process.

        :param port: Local TCP/IP port to which the underlying socket is
                     connected to.
        """
        self.__process = multiprocessing.Process(target=childProcess,
                                                 name=self.__name,
                                                 args=(port, ))
        self.__process.start()
        self.__running = False
        try:
            if sys.platform == "win32":
                self._client = Client(('localhost', port))
            else:
                try:
                    self._client = Client(('', port))
                except OSError:
                    # wait a second before starting, this occur if we were connected to
                    # previously running server that has just closed (we need to wait a
                    # little before starting a new one)
                    time.sleep(1)
                    self._client = Client(('', port))
            logger.info("Connected to Code Completion Server on 127.0.0.1:%d" %
                        port)
            self.__running = True
            self._lock = thread.allocate_lock()
            thread.start_new_thread(self._threadFct, ())
        except OSError:
            logger.exception("Failed to connect to Code Completion Server on "
                             "127.0.0.1:%d" % port)
        return self.__running
Example #25
0
 def __init__(self, maxResources, newResourceFunc):
     self.lock = thread.allocate_lock()
     self.poolEvent = Event()
     self.freeResources = []
     self.busyResources = []
     self.maxResources = maxResources
     self.newResourceFunc = newResourceFunc
Example #26
0
 def test_timeout(self):
     import _thread
     assert isinstance(_thread.TIMEOUT_MAX, float)
     assert _thread.TIMEOUT_MAX > 1000
     lock = _thread.allocate_lock()
     assert lock.acquire() is True
     assert lock.acquire(False) is False
     assert lock.acquire(True, timeout=.1) is False
Example #27
0
 def __init__(self, filename, type):
     self.type = type
     self.filename = filename
     if self.filename:
         self.db = None
     else:
         self.db = {}
     self.lock = _thread.allocate_lock()
Example #28
0
 def _postinit(self):
     # alias all queue methods for faster lookup
     self._popleft = self._queue.popleft
     self._pop = self._queue.pop
     if hasattr(self._queue, 'remove'):
         self._remove = self._queue.remove
     self._wlock = allocate_lock()
     self._append = self._queue.append
 def __init__(self):
     root = Tk()
     root.title(self.title)
     labels = ['Server Name', 'Remote Dir', 'File Name',
               'Local Dir',   'User Name?', 'Password?']
     Form.__init__(self, labels, root)
     self.mutex = _thread.allocate_lock()
     self.threads = 0
Example #30
0
 def InitializeErrorWatcher(self):
     from System.Threading import Thread, ThreadStart
     import _thread            
     self.errorLock = _thread.allocate_lock()
     self.errorString = ""
     th = Thread(ThreadStart(self.WatchErrorStream))
     th.IsBackground = True
     th.Start()
"""
Lab Visualisation & Medical Image Analysis SS2019
Institute of Computer Science II

Author: Christian Breiderhoff
created on June 2019
"""

import config
import argparse
import io_ops
import sys
from _thread import start_new_thread, allocate_lock
import multiprocessing

lock = allocate_lock()
thread_finished = None
show_step_size = 20
show_step_size_tvflow = 500
num_threads = int(multiprocessing.cpu_count())
skip_empty_files = True
skip_existing_files = False


def chunk_dict(dict_in, num_seq):
    avg = len(dict_in) / float(num_seq)
    out = []
    for seq in range(num_seq):
        out.append(dict())
    last = avg
    i = 0
Example #32
0
"""
synchronize access to stdout: because it is shared global,
thread outputs may be intermixed if not synchronized
"""

import _thread as thread, time


def counter(myId, count):  # function run in threads
    for i in range(count):
        time.sleep(1)  # simulate real work
        mutex.acquire()
        print('[%s] => %s' % (myId, i))  # print isn't interrupted now
        mutex.release()


mutex = thread.allocate_lock()  # make a global lock object
for i in range(5):  # spawn 5 threads
    thread.start_new_thread(counter, (i, 5))  # each thread loops 5 times

time.sleep(6)
print('Main thread exiting.')  # don't exit too early
 def __init__(self, num_threads):
     self.num_threads = num_threads
     self.waiting = 0
     self.checkin_mutex = thread.allocate_lock()
     self.checkout_mutex = thread.allocate_lock()
     self.checkout_mutex.acquire()
Example #34
0
import _thread as thread, time
stdoutmutex = thread.allocate_lock()
exitmutexes = [thread.allocate_lock() for i in range(10)]


def counter(myID, count):
    for i in range(count):
        time.sleep(1)
        stdoutmutex.acquire()
        print('[%s] => %s ' % (myID, i))
        stdoutmutex.release()
    exitmutexes[myID].acquire()  #向主线程发送信号。


for i in range(10):
    thread.start_new_thread(counter, (i, 100))

for mutex in exitmutexes:
    while not mutex.locked():
        pass

####time.sleep(6)
print('Main thread exiting.\n')
Example #35
0
class Display:
    lock = _thread.allocate_lock()
    def __init__(self):
        self.alive = False
        self.Led = Pixel()
        self.tem = [[0, 0, 0]] * 25  # 显示缓存区m=
    def stop(self):
        self.alive = False
        if Display.lock.acquire():
            # print("stop")
            Display.lock.release()
    def scroll(self, val, color=Red, delay=150):
        self.stop()
        self.alive = True
        if Display.lock.acquire():
            # print("start")
            _thread.start_new_thread(self._scroll,([val,color,delay]))
            Display.lock.release()
    def Disrupt_Col(color):
        a = color[-1]
        while True:
            if color_num != 1:
                import random
                random.shuffle(color)
                if a != color[0]:
                    break


    def _scroll(self, val, color=Red, delay=150):
        pixel_col = [[0, 0, 0]] * 25  # 显示缓存区m=
        val = str(val) + ' '
        color_num = 1
        if color != Red:
            if isinstance(color[0], list):
                color_num = len(color)
        # self.Disrupt_Col(color) #打乱颜色顺序
        col_cnt = 0
        it = iter(color)
        for val1 in val:
            val2 = CharData[val1]

            if color_num == 1:
                now_col = color
            else:
                if col_cnt < color_num:
                    now_col = next(it)  # 确定当前字符的颜色
                else:
                    col_cnt = 0
                    it = iter(color)
                    now_col = next(it)
                col_cnt += 1

            for i in range(25):  # 为字符的像素点添加颜色
                if val2[i] == 1:
                    pixel_col[i] = now_col
                else:
                    pixel_col[i] = [0, 0, 0]
            if Display.lock.acquire():
                for i in range(6):  # 开始滚动显示
                    if self.alive == False:
                        Display.lock.release()
                        self.clear()
                        _thread.exit()
                    else:
                        for t in range(4):
                            self.tem[20 - (t * 5):20 - (t * 5) + 5] = self.tem[20 -
                                                                               ((t + 1) * 5):20 - ((t + 1) * 5) + 5]
                        # 数据向前移动5位
                        if i == 5:
                            self.tem[0:5] = Zero[0:5]  # 每个字符之间间隔一行
                        else:
                            self.tem[0:5] = pixel_col[20 - (i * 5):20 - (i * 5) + 5]
                        for r in range(25):
                            self.Led.LoadPos(r, self.tem[r])  # 亮度为0
                        self.Led.Show()
                        sleep_ms(delay)
                Display.lock.release()
        _thread.exit()

    def clear(self):
        self.stop()
        self.Led.fill((0, 0, 0))
        self.Led.Show()


    def __show(self, it, color):
        it = iter(it)
        for r in range(25):
            col = next(it)
            self.Led.LoadPos(r, color if col else black)
        self.Led.Show()


    def show(self, images, wait=True, color=Red, *, loop=False, delay=500, clear=False):
        if isinstance(images, str):
            images = CharData[images]
        if isinstance(images, list) and (isinstance(images[0], Image) or isinstance(images[0], list)):
            for i in images:
                self.__show(i, color)
                sleep_ms(delay)
            try:
                while loop:
                    for i in images:
                        self.__show(i, color)
                        sleep_ms(delay)
            except Exception as e:
                self.Led.fill((0, 0, 0))
                self.Led.Show()

        else:
            it = iter(images)
            self.__show(it, color)
            try:
                while loop:
                    self.__show(it, color)
            except Exception as e:
                self.Led.fill((0, 0, 0))
                self.Led.Show()


    def get_pixel(self, x=0, y=0):
        print("get_pixel will be supported in the future.")


    def set_pixel(self, x=0, y=0, value=9):
        print("set_pixel will be supported in the future.")


    def on(self):
        self.clear()


    def off(self):
        self.clear()


    def is_on(self):
        return self.Led != None
Example #36
0
 def __init__(self):
     self.count = 0
     self.mutex = thread.allocate_lock()  # или Threading.semaphore
Example #37
0
#!/usr/bin/python3

"producer and consumer threads communicating with a shared queue"

numconsumers = 2
numproducers = 4
nummessages = 4

import _thread as thread, queue, time
import threading

sameprint = thread.allocate_lock()
dataQueue = queue.Queue()


def producer(idnum, dataqueue):
    for msgnum in range(nummessages):
        time.sleep(idnum)
        dataqueue.put('[producer id=%id, count=%d]' % (idnum, msgnum))


def consumer(idnum, dataqueue):
    while True:
        time.sleep(0.1)
        try:
            data = dataqueue.get(block=False)
        except queue.Empty:
            pass
        else:
            with sameprint:
                print('consumer', idnum, 'got =>', data)
import os
import unittest
import random
from test import support
import _thread as thread
import time
import weakref

from test import lock_tests

NUMTASKS = 10
NUMTRIPS = 3
POLL_SLEEP = 0.010  # seconds = 10 ms

_print_mutex = thread.allocate_lock()


def verbose_print(arg):
    """Helper function for printing out debugging output."""
    if support.verbose:
        with _print_mutex:
            print(arg)


class BasicThreadTest(unittest.TestCase):
    def setUp(self):
        self.done_mutex = thread.allocate_lock()
        self.done_mutex.acquire()
        self.running_mutex = thread.allocate_lock()
        self.random_mutex = thread.allocate_lock()
        self.created = 0
import barometer
import lora_connection
import functions
import _thread
import machine
import socket
import csv
import time

################################################################################
###
### VARIABLES
###

### Threads
lock = _thread.allocate_lock()

### Data
request = None
data = dict()
data["nFinished"] = 0
try:
    count = pycom.nvs_get('count')
except:
    count = 0

### LoRa
lora = LoRa(mode=LoRa.LORA, tx_power=14, sf=9, coding_rate=LoRa.CODING_4_6)
lora.power_mode(LoRa.TX_ONLY)

### Pysense
Example #40
0
import sys
import _thread
import time

from timer import Timer

##TODO: Initialize the following variables
RECEIVER_ADDR = 
SENDER_ADDR = 
SLEEP_INTERVAL = 
TIMEOUT_INTERVAL = 
WINDOW_SIZE = 

# Shared resources across threads
base = 0
mutex = _thread.allocate_lock()
send_timer = Timer(TIMEOUT_INTERVAL)

# Sets the window size
def set_window_size(num_packets):
    global base
    return min(WINDOW_SIZE, num_packets - base)
# Send thread
def send(sock):
    global mutex
    global base
    global send_timer

    ## TODO: Add all the packets and corresponding seq_num to packets
    packets = []
    seq_num = 0
import _thread as thread

stdoutmutex = thread.allocate_lock()
exitmutexes = [False] * 10


def counter(myId, count):
    for i in range(count):
        stdoutmutex.acquire()
        print('[%s]=>%s' % (myId, i))
        stdoutmutex.release()
    exitmutexes[myId] = True


for i in range(10):
    thread.start_new_thread(counter, (i, 100))

while False in exitmutexes:
    pass

print('Main thread existing.')
Example #42
0
 def __init__(self):
     self.lock = _thread.allocate_lock()
     self.lat = None
     self.long = None
     self.h_msl = None  # mm
Example #43
0
            str(dicInfos["CONTROLLER"].getPlaceCode()) + "|" + sens)
        system.addText("LOGS",
                       "Mensagem de atualização enviada ao Servidor!!! ")
    except:
        pass


# ------------------------------------#

dicInfos = {
    "SENSORES": {},
    "ERRO_SENSOR": {},
    "CONTROLLER": newController(),
    "APPARATUS": newApparatus(),
    "PLACES": getPlaces(),
    "MUTEX": _thread.allocate_lock(),
    "SETTINGS": getServerSettings()
}

# conexao para Sensores
dicConn = {
    "SENSOR": socket.socket(socket.AF_INET, socket.SOCK_STREAM),
    "SERVIDOR": None
}
dicConn["SENSOR"].bind((dicInfos["CONTROLLER"].getIpController(),
                        dicInfos["CONTROLLER"].getPort()))
dicConn["SENSOR"].listen(1)

# iniciando interface grafica
root = startTk(geometry="1280x720", title="Controladora", resizable=False)
system = newSystem(root, "Settings/controllerInterfaceSettings.txt",
Example #44
0
# -*- coding: utf-8 -*-
import sys, threading, _thread, time, msvcrt, json
sys.path.append('../../lib/')
import kl_http, kl_db, kl_reg, kl_progress
#from queue import Queue
regex = kl_reg
http = kl_http.kl_http()
http.autoUserAgent = True

progress = kl_progress.kl_progress('')
progress.start()
progress.hide()
#测试代理是否可用
mylock = _thread.allocate_lock()  #线程锁


#测试线程函数
def testProxy(i):
    try:
        global curnum
        #print('正在测试代理:%s:%s %s %s'%(i['ip'],i['port'],i['proxy_type'],i['proxy_area']))
        # sys.stdout.write('正在测试代理:%s:%s ...'%(i['ip'],i['port'])+"\r")
        # sys.stdout.flush()
        progress.settext('正在测试代理:%s:%s' % (i['ip'], i['port']))
        ht = kl_http.kl_http()
        ht.setproxy('', '', '%s:%s' % (i['ip'], i['port']))
        r = ht.geturl('http://proxy.59vip.cn')
        mylock.acquire()  #Get the lock
        if r != None:
            data = r.read().decode()
            if data.find('#ok#') != -1:
Example #45
0
    def __init__(self, current_values):
        self.current_values = current_values
        self.view = BeamerSettingsPageView()

        self.image_loading_lock = thread.allocate_lock()
        thread.start_new_thread(self.load_beamer_images, ())
# объект мьютекса, совместно используемый всеми потоками выполнения, передается
# функции в виде аргумента; для автоматического приобретения/освобождения
# блокировки используется менеджер контекста; чтобы избежать излишней нагрузки
# в цикле ожидания, и для имитации выполнения продолжительных операций добавлен
# вызов функции sleep


import _thread as thread, time


stdoutmutex = thread.allocate_lock()
numthreads = 5
exitmutex = [thread.allocate_lock() for i in range(numthreads)]


def counter(myId, count, mutex):
    for i in range(count):
        time.sleep(1 / (myId+1))
        with mutex:
            print('[%s] => %s' % (myId, i))
    exitmutex[myId].acquire()


for i in range(numthreads):
    thread.start_new_thread(counter, (i, 5, stdoutmutex))

while not all(mutex.locked() for mutex in exitmutex): time.sleep(0.25)
print('Main thread exiting')
Example #47
0
            channel.continueInDialplan()
            on_dtmf_handle.close()
        elif digit == '*':
            channel.play(media='sound:asterisk-friend')
        else:
            channel.play(media='sound:digits/%s' % digit)

    on_dtmf_handle = channel.on_event('ChannelDtmfReceived', on_dtmf)
    channel.answer()
    channel.play(media='sound:hello-world')


client.on_channel_event('StasisStart', on_start)

# Run the WebSocket
sync = _thread.allocate_lock()


def run():
    """Thread for running the Websocket.
    """
    sync.acquire()
    client.run(apps="hello")
    sync.release()


thr = _thread.start_new_thread(run, ())
print("Press enter to exit")
sys.stdin.readline()
client.close()
sync.acquire()
Example #48
0
def _thread_getlock():
    return _thread.allocate_lock()
Example #49
0
import _thread, time

stdout_mutex = _thread.allocate_lock()
numthreads = 5
exit_mutexes = [_thread.allocate_lock() for i in range(numthreads)]


def counter(id, count, mutex):
    for i in range(count):
        time.sleep(1 / (id + 1))
        '''
        __enter__ in 'with' block acquires a block for critical section
        __exit__ releases the last one.
        '''
        with mutex:
            print('[%s] => %s' % (id, i))
    exit_mutexes[id].acquire()


for i in range(numthreads):
    _thread.start_new_thread(counter, (i, numthreads, stdout_mutex))

while not all(mutex.locked() for mutex in exit_mutexes):
    time.sleep(.25)

print('Main thread exiting')
Example #50
0
def get_variable(name):
    g_var = super_var(name)
    if (g_var):
        return g_var.get_value()
    else:
        return None


#--------------------- IOT wifi interface ----------------
m_wifi = codey_wlan()
wifi_connect_time = 3  # s
connecting_ssid = None
connecting_pass = None
m_wifi.wifi_enable()
wifi_sema = _thread.allocate_lock()


def wifi(ssid, password):
    global connecting_ssid
    global connecting_pass
    wifi_sema.acquire(1)
    if (ssid != connecting_ssid) or (password != connecting_pass):
        connecting_ssid = ssid
        connecting_pass = password
        m_wifi.wifi_sta_config(ssid, password)
        m_wifi.wifi_mode_config(m_wifi.STA)
        m_wifi.wifi_start()
        wait_count = 0
        while not wifi_is_connected():
            stime.sleep(0.1)
Example #51
0
 def __init__(self, threads):
     self.__threads = threads
     self.__count = 0
     self.__main = _thread.allocate_lock()
     self.__exit = _thread.allocate_lock()
     self.__exit.acquire()
Example #52
0
    def __init__(self, PORT, startingMode=SAFE_MODE, sim_mode=False):
        """ the constructor which tries to open the
            connection to the robot at port PORT
        """
        # to do: find the shortest safe serial timeout value...
        # to do: use the timeout to do more error checking than
        #        is currently done...
        #
        # the -1 here is because windows starts counting from 1
        # in the hardware control panel, but not in pyserial, it seems

        displayVersion()

        # fields for simulator
        self.in_sim_mode = False
        self.sim_sock = None
        self.sim_host = '127.0.0.1'
        self.sim_port = 65000
        self.maxSensorRetries = MIN_SENSOR_RETRIES

        # if PORT is the string 'simulated' (or any string for the moment)
        # we use our SRSerial class
        self.comPort = PORT  #we want to keep track of the port number for reconnect() calls
        print('PORT is', PORT)
        if type(PORT) == type('string'):
            if PORT == 'sim':
                self.init_sim_mode()
                self.ser = None
            else:
                # for Mac/Linux - use whole port name
                # print 'In Mac/Linux mode...'
                self.ser = serial.Serial(PORT, baudrate=57600, timeout=0.5)
                # otherwise, we try to open the numeric serial port...
                if (sim_mode):
                    self.init_sim_mode()
        else:
            # print 'In Windows mode...'
            try:
                self.ser = serial.Serial(PORT - 1, baudrate=57600, timeout=0.5)
                if (sim_mode):
                    self.init_sim_mode()
            except serial.SerialException:
                print(
                    "unable to access the serial port - please cycle the robot's power"
                )

        # did the serial port actually open?
        if self.in_sim_mode:
            print("In simulator mode")
        elif self.ser.isOpen():
            print('Serial port did open on iRobot Create...')
        else:
            print('Serial port did NOT open, check the')
            print('  - port number')
            print('  - physical connection')
            print(
                '  - baud rate of the roomba (it\'s _possible_, if unlikely,')
            print('              that it might be set to 19200 instead')
            print('              of the default 57600 - removing and')
            print('              reinstalling the battery should reset it.')

        # define the class' Open Interface mode
        self.sciMode = OFF_MODE

        if (startingMode == SAFE_MODE):
            print('Putting the robot into safe mode...')
            self.toSafeMode()
            time.sleep(0.3)
        if (startingMode == FULL_MODE):
            print('Putting the robot into full mode...')
            self.toSafeMode()
            time.sleep(0.3)
            self.toFullMode()

        self.serialLock = _thread.allocate_lock()
Example #53
0
SEQ_SIZE = 4
HASH_SIZE = 56
PACKET_SIZE = 1988
#Packet Length specify the size of the whole packet include header 2048 B
PACKET_LENGTH = PACKET_SIZE + SEQ_SIZE + HASH_SIZE

filename1 = ''  # read file
filename2 = ''  #  write file

# NAME
NAME_SENDER = b'sender'
NAME_REC = b'reciever'

# global
base = 0
ack_thread = _thread.allocate_lock()

#set timeout duration for timer
timer = Timer(TIMEOUT_DURATION)


# extract the packet
def packet_unpack(data):
    # bytes from 0 to HASH_SIZE-1: checksum
    checksum = data[:HASH_SIZE]
    # byts from HASH_SIZE to SEQ_SIZE + HASH_SIZE-1: sequence number
    # remaim bytes are data
    seq_num = int.from_bytes(data[HASH_SIZE:SEQ_SIZE + HASH_SIZE],
                             byteorder='little',
                             signed=True)
"""
синхронизирует доступ к stdout: так как это общий глобальный объект, данные,
которые выводятся из потоков выполнения, могут перемешиваться, если не
синхронизировать операции
"""

import _thread as thread, time

mutex = thread.allocate_lock()  # создать объект блокировки


def counter(myId, count):  # эта функция выполняется в потоках

    for i in range(count):
        time.sleep(1)  #   имитировать работу
        mutex.acquire()  # теперь работа
        print(f"[{myId}] => {i}")  # функции print
        mutex.release()  # не будет прерываться


for i in range(5):
    thread.start_new_thread(counter, (i, 5))  #

time.sleep(6)
print('Main thread exiting.')
Example #55
0
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
# ----------------------------------------------------------------------------
import subprocess
import multiprocessing
import _thread as thread
from gspylib.inspection.common.CheckItem import BaseItem
from gspylib.inspection.common.CheckResult import ResultStatus
from gspylib.threads.parallelTool import parallelTool
from gspylib.os.gsnetwork import g_network

DEFAULT_PARALLEL_NUM = 12
g_lock = thread.allocate_lock()
noPassIPs = []


class CheckPing(BaseItem):
    def __init__(self):
        super(CheckPing, self).__init__(self.__class__.__name__)

    def doCheck(self):
        global noPassIPs
        allIP = []
        LocalNodeInfo = self.cluster.getDbNodeByName(self.host)
        allIP += LocalNodeInfo.backIps
        allIP += LocalNodeInfo.sshIps
        for dbInstance in LocalNodeInfo.datanodes:
            allIP += dbInstance.haIps
Example #56
0
def thread1():
    global lock
    lock = _thread.allocate_lock()
    lock.acquire()
    time.sleep(5)
    lock.release()
Example #57
0
"""
The sign display server
by Thomas(Sascha) Alexander Steinholz
"""

from multiprocessing.connection import Listener
from time import sleep
from _thread import start_new_thread, allocate_lock

SERVER_PORT = 7980
parking_access_lock = allocate_lock()
parking_directory = []
progress_bars = []


def start_server():
    """ Add new connections as they come in. """
    server = Listener(('', SERVER_PORT))
    print("[+] Server Created.")
    while True:
        connection = server.accept()
        print("[+] Connected to Parking Sensor",
              str(connection.fileno()) + ".")
        start_new_thread(client_thread, (connection, ))


def update_parking(identifier, direction):
    """ Safely update the parking_directory slot count. """
    with parking_access_lock:
        # Find the identifier in the directory.
        for lot in parking_directory:
Example #58
0
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.

import os
import sys
import unittest
import _thread

CP16623_LOCK = _thread.allocate_lock()

from iptest import IronPythonTestCase, is_cli, is_cpython, is_netcoreapp, is_posix, run_test, skipUnlessIronPython

class FileTest(IronPythonTestCase):

    def setUp(self):
        super(FileTest, self).setUp()

        self.temp_file = os.path.join(self.temporary_dir, "temp_%d.dat" % os.getpid())
        self.rng_seed = 0

        # The set of read modes we wish to test. Each tuple consists of a human readable
        # name for the mode followed by the corresponding mode string that will be
        # passed to the file constructor.
        self.read_modes = (("binary", "rb"), ("text", "r"), ("universal", "rU"))

        # Same deal as above but for write modes. Note that writing doesn't support a
        # universal newline mode.
        self.write_modes = (("binary", "wb"), ("text", "w"))

    def tearDown(self):
Example #59
0
 def __init__(self) :
     self._lock  = allocate_lock()
     self._first = None
     self._last  = None