如何不陷入无限阻塞功能?

问题描述 投票:0回答:1

我不确定使用什么是正确的术语。但我的例子应该清除它。

我想听一个Reddit comment stream

此流在发布到reddit(/ r / askReddit和/ r / worldNews)时实时收到评论,因此我不必轮询服务器。

但是,这个函数是阻塞的,我需要把它放到几个线程中。

这是我到目前为止所拥有的:

#! usr/bin/python3
from multiprocessing.dummy import Pool
import praw

def process_item(self, stream):
    # Display the comment
    for comment in stream:
        print(comment.permalink)

def get_streams(reddit):
    # Listen for comments from these two subReddits:
    streams = [
        reddit.subreddit('AskReddit').stream.comments(skip_existing=True),
        reddit.subreddit('worldnews').stream.comments(skip_existing=True)            
    ]
    pool = Pool(4)
    print('waiting for comments...')
    results = pool.map(self.process_item, streams)

    # But I want to do tons of other things down here or in `main()`.
 # The code will never reach down here because it's always listening for comments.

我能看到的唯一解决方法是将我的整个程序逻辑放入process_item(),但这看起来真的很愚蠢。

我想我希望process_item继续在后台添加注释到列表,然后我可以按照我认为合适的方式处理这些注释。但我不需要陷入process_item()

当程序正在做其他事情时,列表正在排队等待作业,而程序正在做其他事情。

可能?如果是这样,你能给我一些关于模式的提示吗?

我是线程的新手。

python python-multithreading blocking nonblocking
1个回答
0
投票

阅读更多关于pub / sub模式的信息。如果你想要线程使用线程模块。

多处理是os进程。进程和线程是不同的东西。如果你想线程使用线程(当进程数据考虑GIL时)

做任何事情:

你可以启动一些线程从流中读取数据并将消息放到LIFO数据结构中启动一些线程从LIFO数据结构读取数据来处理你的数据

© www.soinside.com 2019 - 2024. All rights reserved.