无法在mutithreading模式下使用aiomysql

时间:2018-03-09 18:05:47

标签: multithreading python-3.x python-asyncio

我想在mutithreading模式下使用aiomysql。然后它失败了。这是我的代码。

import asyncio
import aiomysql

from threading import Thread

def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

async def create_pool(loop, **kw):
    global __pool
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop
    )

async def select():
    global __pool
    async with __pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            print('ok here')
            await cur.execute('select * from test')
            print('failed here')
            rs = await cur.fetchall()
            print('rows returned: %s' % len(rs))

loop = asyncio.get_event_loop()
new_loop = asyncio.new_event_loop()
t = Thread(target=start_loop, args=(new_loop,))
loop.run_until_complete(create_pool(loop, user='user', password='password', db='test'))
t.start()
asyncio.run_coroutine_threadsafe(select(), new_loop)

'好的,这里'可以打印,而在这里失败'可'吨。所以它失败了#34;等待cur.execute(' select * from test')"。如果我使用create_pool并在一个线程中选择它,它将起作用。所以它让我很困惑为什么它在多线程模式下失败了。

感谢。

0 个答案:

没有答案