• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python multiprocessing.Value类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中multiprocessing.Value的典型用法代码示例。如果您正苦于以下问题:Python Value类的具体用法?Python Value怎么用?Python Value使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Value类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: setup_heartbeat

    def setup_heartbeat(self, client_controller):
        cond = multiprocessing.Condition()
        s_init_finish = Value('i', 0)

        do_sample = Value('i', 0)
        do_sample_lock = Lock()

        server_process = multiprocessing.Process(
                target=self.server_heart_beat, 
                args=(cond, s_init_finish, do_sample, do_sample_lock))
        server_process.daemon = False
        server_process.start()

        logger.info("Waiting for server init ...")
        cond.acquire()
        while (s_init_finish.value == 0):
            cond.wait()
        if s_init_finish.value == 5:
            logger.error("Waiting for server init ... FAIL")
            raise RuntimeError("server init failed.")
        cond.release()
        logger.info("Waiting for server init ... Done")
        
        # let all clients start running the benchmark
        client_controller.client_run(do_sample, do_sample_lock)
        cond.acquire()
        s_init_finish.value = 0
        cond.release()
        return server_process
开发者ID:EvilMcJerkface,项目名称:rococo,代码行数:29,代码来源:run.py


示例2: run_with_exception_except_test

    def run_with_exception_except_test(self):
        """ Subclass StoppableExceptionThread and raise exception in method `run_with_exception` """
        class IncrementThread(StoppableExceptionThread):
            """ Used to test _stop in `run` """
            def __init__(self, *args, **kwargs):
                self.x = args[0]
                StoppableExceptionThread.__init__(self, *args[1:], **kwargs)

            def run_with_exception(self):
                while not self._stop.is_set():
                    with self.x.get_lock():
                        self.x.value += 1
                        if self.x.value > 5:
                            raise ValueError('x > 5')

        x = Value('i', 0)
        st = IncrementThread(x)
        st.start()
        sleep(1)
        assert_equals(st.stopped, False)
        with self.assertRaises(ValueError):
            st.join()
        assert_equals(st.is_alive(), False)
        with x.get_lock():
            assert_equals(x.value, 6)
开发者ID:fraserharris,项目名称:threading-extensions,代码行数:25,代码来源:threading_extension_tests.py


示例3: Counter

class Counter(object):
    """
    A process-safe counter providing atomic incrementAndGet() and value() functions
    """
    def __init__(self, initval=0):
        """
        Initialize this counter
        Args:
            initval (int): set the initialize value of the counter
        """
        self.val = Value('i', initval)

    def incrementAndGet(self):
        """
        Atomically increment this counter, and return the new value stored.

        Returns:
            int: The updated value of this counter.
        """
        with self.val.get_lock():
            self.val.value += 1
            return self.val.value

    def value(self):
        """
        Atomically get the current value of this counter.

        Returns:
            int: The current value of this counter.
        """
        with self.val.get_lock():
            return self.val.value
开发者ID:jasonsbrooks,项目名称:ARTIST,代码行数:32,代码来源:counter.py


示例4: run_stop_test

    def run_stop_test(self):
        """ Subclass StoppableThread and stop method `run` """
        class IncrementThread(StoppableThread):
            """ Used to test _stop in `run` """
            def __init__(self, *args, **kwargs):
                self.x = args[0]
                super(IncrementThread, self).__init__(*args[1:], **kwargs)

            def run(self):
                while not self._stop.is_set():
                    with self.x.get_lock():
                        self.x.value += 1

        x = Value('i', 0)
        st = IncrementThread(x)
        st.start()
        assert_equals(st.stopped, False)
        assert_equals(st.is_alive(), True)
        sleep(0.5)
        st.stop()
        assert_equals(st.stopped, True)
        st.join()
        assert_equals(st.is_alive(), False)
        with x.get_lock():
            assert_greater(x.value, 0)
开发者ID:fraserharris,项目名称:threading-extensions,代码行数:25,代码来源:threading_extension_tests.py


示例5: main

def main():
    settings.setup()
    try:
        import miniupnpc
    except:
        safeprint("Dependency miniupnpc is not installed. Running in outbound only mode")
        settings.config['outbound'] = True
    safeprint("settings are:")
    safeprint(settings.config)
    queue = Queue()
    live = Value('b',True)
    ear = listener(settings.config['port'],settings.config['outbound'],queue,live,settings.config['server'])
    ear.daemon = True
    ear.start()
    feedback = []
    stamp = time()
    while queue.empty():
        if time() - 5 > stamp:
            break #pragma: no cover
    try:
        feedback = queue.get(False)
    except: #pragma: no cover
        safeprint("No feedback received from listener")
    ext_ip = ""     #Does this affect peers?
    ext_port = -1   #Does this affect peers?
    if feedback != []:
        settings.outbound = feedback[0]
        if settings.outbound is not True:
            ext_ip = feedback[1]
            ext_port = feedback[2]
    initializePeerConnections(settings.config['port'], ext_ip, ext_port)
    live.value = False
开发者ID:Distelli,项目名称:Senior-Project,代码行数:32,代码来源:main.py


示例6: execute_task

    def execute_task(self, website: Website, busy: Value, post_id: str, comment_id: str):
        busy.value = 1
        if os.path.exists("data.json"):
            os.remove("data.json")
        print("Started crawling task")
        process = CrawlerProcess(get_project_settings())
        process.crawl("od_links", base_url=website.url)
        process.start()
        print("Done crawling")

        self.db.import_json("data.json", website)
        os.remove("data.json")
        print("Imported in SQLite3")

        if post_id:
            # Reply to post
            stats = self.db.get_website_stats(website.id)
            comment = self.reddit_bot.get_comment({"": stats}, website.id)
            print(comment)
            if "total_size" in stats and stats["total_size"] > 10000000:
                post = self.reddit_bot.reddit.submission(post_id)
                self.reddit_bot.reply(post, comment)
                pass
            else:
                self.reddit_bot.log_crawl(post_id)

        elif comment_id:
            # Reply to comment
            stats = self.db.get_website_stats(website.id)
            comment = self.reddit_bot.get_comment({"There you go!": stats}, website.id)
            print(comment)
            reddit_comment = self.reddit_bot.reddit.comment(comment_id)
            self.reddit_bot.reply(reddit_comment, comment)
        busy.value = 0
        print("Done crawling task")
开发者ID:ohhdemgirls,项目名称:od-database,代码行数:35,代码来源:task.py


示例7: main

def main():
    #Begin Init
    settings.setup()
    from common.safeprint import safeprint
    try:
        import miniupnpc
    except:
        safeprint("Dependency miniupnpc is not installed. Running in outbound only mode")
        settings.config['outbound'] = True
    safeprint("settings are:")
    safeprint(settings.config)
    queue = Queue()
    live = Value('b',True)
    ear = listener(settings.config['port'],settings.config['outbound'],queue,live,settings.config['server'])
    ear.daemon = True
    ear.items = sync()
    ear.start()
    mouth = propagator(settings.config['port'] + 1, live)
    mouth.daemon = True
    mouth.items = ear.items
    mouth.start()
    feedback = []
    stamp = time()
    while queue.empty():
        if time() - 5 > stamp:
            break #pragma: no cover
    try:
        feedback = queue.get(False)
    except: #pragma: no cover
        safeprint("No feedback received from listener")
    ext_ip = ""     #Does this affect peers?
    ext_port = -1   #Does this affect peers?
    if feedback != []:
        settings.outbound = feedback[0]
        if settings.outbound is not True:
            ext_ip = feedback[1]
            ext_port = feedback[2]
    initializePeerConnections(settings.config['port'], ext_ip, ext_port)
    #End Init
    
    #Begin main loop
    if settings.config.get('seed'):
        safeprint("Seed mode activated")
        try:
            while True and not settings.config.get('test'):
                sleep(0.1)
        except KeyboardInterrupt:
            safeprint("Keyboard Interrupt")
    elif settings.config.get('server'):
        safeprint("Server mode activated")
    else:
        safeprint("Client mode activated")
    #End main loop
    
    #Begin shutdown
    safeprint("Beginning exit process")
    live.value = False
    settings.saveSettings()
    saveToFile()
    bounty.saveToFile()
开发者ID:leftees,项目名称:Senior-Project,代码行数:60,代码来源:main.py


示例8: call

def call(args, stdout=None, stderr=None, stdin=None, daemonize=False,
         preexec_fn=None, shell=False, cwd=None, env=None):
    """
    Run an external command in a separate process and detach it from the current process. Excepting
    `stdout`, `stderr`, and `stdin` all file descriptors are closed after forking. If `daemonize`
    is True then the parent process exits. All stdio is redirected to `os.devnull` unless
    specified. The `preexec_fn`, `shell`, `cwd`, and `env` parameters are the same as their `Popen`
    counterparts. Return the PID of the child process if not daemonized.
    """
    stream = lambda s, m: s is None and os.open(os.devnull, m) or s
    stdout = stream(stdout, os.O_WRONLY)
    stderr = stream(stderr, os.O_WRONLY)
    stdin = stream(stdin, os.O_RDONLY)

    shared_pid = Value('i', 0)
    pid = os.fork()
    if pid > 0:
        os.waitpid(pid, 0)
        child_pid = shared_pid.value
        del shared_pid
        if daemonize:
            sys.exit(0)
        return child_pid
    else:
        os.setsid()
        proc = subprocess.Popen(args, stdout=stdout, stderr=stderr, stdin=stdin, close_fds=True,
                                preexec_fn=preexec_fn, shell=shell, cwd=cwd, env=env)
        shared_pid.value = proc.pid
        os._exit(0)
开发者ID:BlueDragonX,项目名称:detach,代码行数:29,代码来源:detach.py


示例9: _init_visualization_and_io

    def _init_visualization_and_io(self, sim):
        if self.config.output:
            output_cls = io.format_name_to_cls[self.config.output_format]
        else:
            output_cls = io.LBOutput

        if self.config.mode != 'visualization':
            return lambda subdomain: output_cls(self.config, subdomain.id)

        # basic_fields = sim.fields()
        # XXX compute total storage requirements

        for subdomain in self.subdomains:
            size = reduce(operator.mul, subdomain.size)
            vis_lock = mp.Lock()
            vis_buffer = Array(ctypes.c_float, size, lock=vis_lock)
            vis_geo_buffer = Array(ctypes.c_uint8, size, lock=vis_lock)
            subdomain.set_vis_buffers(vis_buffer, vis_geo_buffer)

        vis_lock = mp.Lock()
        vis_config = Value(io.VisConfig, lock=vis_lock)
        vis_config.iteration = -1
        vis_config.field_name = ''
        vis_config.all_blocks = False

        # Start the visualizatione engine.
        vis_class = None
        for engine in util.get_visualization_engines():
            if engine.name == self.config.vis_engine:
                vis_class = engine
                break

        if vis_class is None:
            self.config.logger.warning('Requested visualization engine not '
                                       'available.')
            try:
                vis_class = util.get_visualization_engines().next()
            except StopIteration:
                self.config.logger.warning(
                    'No visualization backends available. Falling back to '
                    'batch mode.')
                self.config.mode = 'batch'
                return lambda subdomain: output_cls(self.config, subdomain.id)

        # Event to signal that the visualization process should be terminated.
        self._vis_quit_event = Event()
        self._vis_process = Process(
                target=lambda: vis_class(
                    self.config, self.subdomains, self._vis_quit_event,
                    self._quit_event, vis_config).run(),
                name='VisEngine')
        self._vis_process.start()

        return lambda subdomain: io.VisualizationWrapper(
                self.config, subdomain, vis_config, output_cls)
开发者ID:Mokosha,项目名称:sailfish,代码行数:55,代码来源:master.py


示例10: main

def main():
	running = Value(c_int, 1)
	readQueue = Queue()
	reader = Process(target = Reader("/dev/ttyUSB0", 9600), args = (running, readQueue))
	worker = Process(target = Worker(), args = (running, readQueue))
	reader.start()
	worker.start()
	time.sleep(5)
	running.value = 0
	reader.join()
	worker.join()
开发者ID:AnthonyWalton1,项目名称:ARBI,代码行数:11,代码来源:uartTest.py


示例11: __init__

    def __init__(self, nomenclature="", width=0., height=0.):

        Device.__init__(self, nomenclature, width, height)
        self.xpos_left = -0.5 * width
        self.xpos_right = 0.5 * width
        self.ypos_bottom = -0.5 * height
        self.ypos_top = 0.5 * height
        self.count_left = Value('i', 0)
        self.count_right = Value('i', 0)
        self.count_bottom = Value('i', 0)
        self.count_top = Value('i', 0)
开发者ID:StephanII,项目名称:accelerator-toolkit,代码行数:11,代码来源:diagnostic.py


示例12: _init_visualization_and_io

    def _init_visualization_and_io(self, sim):
        if self.config.output:
            output_cls = io.format_name_to_cls[self.config.output_format]
        else:
            # Dummy output class. Does not actually save data, but does provide
            # utility functions common to all output classes.
            output_cls = io.LBOutput

        if self.config.mode != 'visualization':
            return lambda subdomain: output_cls(self.config, subdomain.id)

        # XXX compute total storage requirements
        self._vis_geo_queues = []
        for subdomain in self.subdomain_specs:
            self._vis_geo_queues.append(subdomain.init_visualization())

        vis_lock = mp.Lock()
        vis_config = Value(io.VisConfig, lock=vis_lock)
        vis_config.iteration = -1
        vis_config.field_name = ''
        vis_config.all_subdomains = False

        # Start the visualizatione engine.
        vis_class = None
        for engine in util.get_visualization_engines():
            if engine.name == self.config.vis_engine:
                vis_class = engine
                break

        if vis_class is None:
            self.config.logger.warning('Requested visualization engine not '
                                       'available.')
            try:
                vis_class = util.get_visualization_engines().next()
            except StopIteration:
                self.config.logger.warning(
                    'No visualization backends available. Falling back to '
                    'batch mode.')
                self.config.mode = 'batch'
                return lambda subdomain: output_cls(self.config, subdomain.id)

        # Event to signal that the visualization process should be terminated.
        self._vis_quit_event = Event()
        self._vis_process = Process(
                target=lambda: vis_class(
                    self.config, self.subdomain_specs, self._vis_quit_event,
                    self._quit_event, vis_config, self._vis_geo_queues).run(),
                name='VisEngine')
        self._vis_process.start()

        return lambda subdomain: io.VisualizationWrapper(
                self.config, subdomain, vis_config, output_cls)
开发者ID:PokerN,项目名称:sailfish,代码行数:52,代码来源:master.py


示例13: Control

class Control(object):
    """Shared (long) value for passing control information between main and
    worker threads.
    
    Args:
        initial_value: Initial value of the shared control variable.
    """
    def __init__(self, initial_value=CONTROL_ACTIVE):
        self.control = Value('l', initial_value)
    
    def check_value(self, value, lock=False):
        """Check that the current control value == `value`.
        
        Args:
            value: The value to check.
            lock: Whether to lock the shared variable before checking.
        
        Returns:
            True if the values are equal.
        """
        return self.get_value(lock=lock) == value
    
    def check_value_positive(self, lock=False):
        """Check that the current control value is positive.
        
        Args:
            lock: Whether to lock the shared variable before checking.
        """
        return self.get_value(lock=lock) > 0
    
    def get_value(self, lock=True):
        """Returns the current control value.
        
        Args:
            lock: Whether to lock the shared variable before checking.
        """
        if lock:
            with self.control.get_lock():
                return self.control.value
        else:
            return self.control.value
    
    def set_value(self, value):
        """Set the control value. The shared variable is always locked.
        
        Args:
            value: The value to set.
        """
        with self.control.get_lock():
            self.control.value = value
开发者ID:jdidion,项目名称:atropos,代码行数:50,代码来源:multicore.py


示例14: __init__

class Counter:
	def __init__(self):
		self.value = Value(ctypes.c_int)

	def __enter__(self):
		with self.value.get_lock():
			self.value.value += 1

	def __exit__(self, exc_type, exc_val, exc_tb):
		with self.value.get_lock():
			self.value.value -= 1

	def __repr__(self):
		return str(self.value.value)
开发者ID:gandalfvn,项目名称:simple_dqn-1,代码行数:14,代码来源:game.py


示例15: camstream

def camstream():
  print "CAMera STREAMer (OpenCV " + cv2.__version__ + ")"
  print "main(): OS: {}".format(os.name)
  
  # * Start CameraStreamer process
  print "main(): Starting CameraStreamer process..."
  if os.name == 'nt':  # [Windows]
    # ** Create shared objects (NOTE only necessary on Windows since it uses a different multiprocessing implementation)
    print "main(): [Windows] Creating shared objects..."
    # *** Stay alive flag
    stayAliveObj = Value(c_bool, True)
    
    # *** Frame counter
    frameCountObj = Value('i', 0)
    
    # *** Image array
    image = np.zeros((camera_frame_height, camera_frame_width, camera_frame_depth), dtype=np.uint8)
    imageShape = image.shape
    imageSize = image.size
    image.shape = imageSize  # flatten numpy array
    imageObj = Array(c_ubyte, image)  # create a synchronized shared array
    
    # *** Image shape
    imageShapeObj = Array('i', imageShape)
    cameraStreamerProcess = CameraStreamer(stayAliveObj, frameCountObj, imageObj, imageShapeObj)
  else:  # [POSIX]
    cameraStreamerProcess = CameraStreamer()
    # ** Grab generated shared objects to share with other child processes
    print "main(): [POSIX] Getting shared objects from CameraStreamer..."
    stayAliveObj = cameraStreamerProcess.stayAliveObj
    frameCountObj = cameraStreamerProcess.frameCountObj
    imageObj = cameraStreamerProcess.imageObj
    imageShapeObj = cameraStreamerProcess.imageShapeObj
  cameraStreamerProcess.start()
  
  # * Start StreamViewer process
  print "main(): Starting StreamViewer process..."
  streamViewerProcess = StreamViewer(stayAliveObj, frameCountObj, imageObj, imageShapeObj)
  streamViewerProcess.start()
  
  # * Wait for child processes to finish
  print "main(): Waiting for child processes to finish..."
  try:
    streamViewerProcess.join()
    cameraStreamerProcess.join()
  except KeyboardInterrupt:
    stayAliveObj.value = False
    streamViewerProcess.join()
    cameraStreamerProcess.join()
  print "main(): Done."
开发者ID:napratin,项目名称:lumos,代码行数:50,代码来源:camstream.py


示例16: start

    def start(self, reload_from=None):
        """Start this server process.

        :param int reload_from: Optional, the PID of a running game server
                                process that this process should reload from
        :returns None:

        """
        assert not self._process, "server instance already started"
        pid = Value("i")
        self._process = Process(target=self._start,
                                args=(pid, socket_queue),
                                kwargs={"reload_from": reload_from})
        self._process.start()
        pid.value = self._process.pid
开发者ID:seanohue,项目名称:atria,代码行数:15,代码来源:nanny.py


示例17: send_mldquery_regularly

    def send_mldquery_regularly(self):
        self.logger.debug("")

        requraly_query_type = self.config[const.REGURALY_QUERY_TYPE]
        reguraly_query_interval = self.config[const.REGURALY_QUERY_INTERVAL]
        mc_query_interval = self.config[const.MC_QUERY_INTERVAL]

        # 初回送信前に定期送信クエリの送信間隔の1/4秒待つ
        time.sleep(reguraly_query_interval / 4)

        # General Query
        if requraly_query_type == self.GENERAL_QUERY:
            self.logger.debug("create general query")
            mc_info = {const.MC_TAG_MC_ADDR: const.DELIMIT_DOUBLE_COLON,
                       const.MC_TAG_SERV_IP: None}
            while self.SEND_LOOP:
                self.send_mldquery([mc_info])
                # タイムアウトチェック
                self.check_user_timeout()
                time.sleep(reguraly_query_interval - self.QUERY_QRV)

        # Specific Query
        elif requraly_query_type == self.SPECIFIC_QUERY:
            self.logger.debug("create specific query")
            next_interval = Value(ctypes.c_bool, False)

            while self.SEND_LOOP:
                query_proc = Process(
                    target=self.wait_query_interval,
                    args=(next_interval, reguraly_query_interval))
                query_proc.daemon = True
                query_proc.start()
                self.logger.debug(
                    "next_interval : %s", str(next_interval.value))
                self.send_mldquery(
                    self.mc_info_list, mc_query_interval, next_interval)
                # タイムアウトチェック
                self.check_user_timeout()

                # 定期送信クエリの送信間隔が過ぎていない場合は待ち
                if not next_interval.value:
                    self.logger.debug(
                        "waiting query interval(%d sec)...",
                        reguraly_query_interval)
                    query_proc.join()

                next_interval.value = False
                query_proc.terminate()
开发者ID:ntts-clo,项目名称:mld-ryu,代码行数:48,代码来源:mld_process.py


示例18: Transformator

class Transformator(Device):
    def __init__(self, nomenclature="", width=0., height=0.):

        Device.__init__(self, nomenclature, width, height)
        self.count = Value('i', 0)

    def __repr__(self):

        r = str(self) + "("
        r += "width=" + str(self.width) + "m, "
        r += "height=" + str(self.height) + "m, "
        r += "length=" + str(self.length) + "m, "
        r += "count=" + str(self.count.value) + ")"
        return r

    def transport(self, particle):
        if not self.is_particle_lost(particle):
            with self.count.get_lock():
                self.count.value += 1
            if self.next:
                return self.next.transport(particle)

    def reset(self):

        self.count.value = 0
        if self.next:
            self.next.reset()
开发者ID:StephanII,项目名称:accelerator-toolkit,代码行数:27,代码来源:diagnostic.py


示例19: __init__

    def __init__(self, world_class, opt, agents):
        self.inner_world = world_class(opt, agents)

        self.queued_items = Semaphore(0)  # counts num exs to be processed
        self.epochDone = Condition()  # notifies when exs are finished
        self.terminate = Value('b', False)  # tells threads when to shut down
        self.cnt = Value('i', 0)  # number of exs that remain to be processed

        self.threads = []
        for i in range(opt['numthreads']):
            self.threads.append(HogwildProcess(i, world_class, opt,
                                               agents, self.queued_items,
                                               self.epochDone, self.terminate,
                                               self.cnt))
        for t in self.threads:
            t.start()
开发者ID:jojonki,项目名称:ParlAI,代码行数:16,代码来源:worlds.py


示例20: __init__

 def __init__(self, initval=0):
     """
     Initialize this counter
     Args:
         initval (int): set the initialize value of the counter
     """
     self.val = Value('i', initval)
开发者ID:jasonsbrooks,项目名称:ARTIST,代码行数:7,代码来源:counter.py



注:本文中的multiprocessing.Value类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python connection.Client类代码示例发布时间:2022-05-27
下一篇:
Python multiprocessing.SimpleQueue类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap