我写我的代码到select在3个线程中并发单线程一个连接;我发现它比1个线程慢;多线程读取会导致性能下降吗?
这里是我的测试数据:
这是一个表(索引uint32)与100000项;
当我在3个一线选择 10万项目(所有项目):
0: 1443185531.782627, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read ready
1: 1443185531.782634, cost 0.000007, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read start
2: 1443185533.365550, cost 1.582916, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read end
0: 1443185531.772624, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read ready
1: 1443185531.782659, cost 0.010035, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read start
2: 1443185533.372972, cost 1.590313, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read end
0: 1443185531.773191, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read ready
1: 1443185531.782636, cost 0.009445, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read start
2: 1443185533.393716, cost 1.611080, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read end
你可以看到它的成本1.5秒的平均水平。
但是,当我更改为选择 10万项目(所有项目)在1线:
0: 1443185738.427020, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read ready
1: 1443185738.427106, cost 0.000086, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read start
2: 1443185739.020410, cost 0.593304, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read end
的成本达到0.5秒。
所以我混淆了多线程阅读会减慢sqlite3的性能。
据我所知,阅读使用shared-mutex,它可以在多线程中共享。性能下降不应该发生。
有人可以解决我的困惑吗?
附加:
sqlite3的是在WAL,SQLITE_CONFIG_MULTITHREAD模式,无需任何手动互斥。
附加:
我运行这样我在3个线程代码。
//objc code
dispatch_async(name1, ^{
select * in conn1
}
dispatch_async(name2, ^{
select * in conn2
}
dispatch_async(name3, ^{
select * in conn3
}
而不是在每个线程中使用相同的连接(线程不能同时使用),请为每个线程创建一个连接。 –
我明白每个线程都有自己的句柄sqlite(单线程一个句柄)。您正在以错误的方式使用线程。你让你的软件做了3次相同的工作,所以它花了更多的时间。 – user430051
@ColonelThirtyTwo我在每个线程中都使用自己的连接。 (写单线程一连接) –