如何确定某个函数或者某个变量正在被多个线程使用呢?

2015-12-31 18:08:33 +08:00
 quietin
在 python 中如何确定某个函数或者某个变量正在被多个线程(或进程)使用呢?
举例场景,像`sqlalchemy`里用多线程共享一个数据库连接提交就会提示你正在用多个线程,提交不被允许。这是如何实现的呢?

反过来,还想问一下,如何让一个变量(或函数)变成线程或进程独占的呢?
比如在线程中,是不是用 thread local 就可以了, 比如这样,在一线程中独占变量`a`
```
import local
dummy = local()
dummy.number = a
del a
```
但这好像得保证当前线程最先执行才可以

希望能和大家交流讨论下,欢迎给出想法建议:)
2969 次点击
所在节点    Python
12 条回复
yangtukun1412
2015-12-31 20:00:16 +08:00
用 threading.RLock 应该可以实现
quietin
2015-12-31 20:55:08 +08:00
第一个问题谁能给个解答。。。
sincway
2015-12-31 22:55:36 +08:00
我觉得信号量可以实现
quietin
2015-12-31 23:03:42 +08:00
@sincway 可否稍微具体一些呢
sincway
2015-12-31 23:46:13 +08:00
@quietin 搜索 Python semaphore 即可。信号量可以保证只允许指定数目的进程或者线程访问某个资源,超过数量就会被阻塞。如果设置为 1 就是只允许一个同时访问。
gamexg
2016-01-01 00:14:18 +08:00
内部保存当前操作线程即可,别忘了锁
gamexg
2016-01-01 00:17:15 +08:00
对了,可以写一个修饰器,对所有公开函数加可重入锁。
可能有这种库了。
boyhailong
2016-01-01 19:00:59 +08:00
貌似大家都在回答第二个问题,它的确不难
至于第一个 你指的是运行期判断是不是有多线程调用吗 这个可以在函数或者变量前加个线程 id 的记录 如果有多于两个不同的线程 id 就说明在发生多线程调用啦 其实也很简单。
quietin
2016-01-01 21:19:15 +08:00
@boyhailong 谢谢回复。是的,可以用 threading.get_current().ident 得到线程标识
quietin
2016-01-01 22:10:10 +08:00
@boyhailong 我发现了一个问题,标识必须得么线程本身,不能用 ident ,并发四线程的时候
<Thread(Thread-1, started 123145306509312)>
<Thread(Thread-2, started 123145306509312)>
<Thread(Thread-3, started 123145306509312)>
<Thread(Thread-4, started 123145306509312)>
它们的 ident 都是一样的。。。
boyhailong
2016-01-02 19:35:59 +08:00
@quietin python 线程是可以设置 name 的 最简单的就是启动线程的时候 设置 运行期获取就可以
具体可以参考: http://www.tutorialspoint.com/python/python_multithreading.html

In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows:

run(): The run() method is the entry point for a thread.

start(): The start() method starts a thread by calling the run method.

join([time]): The join() waits for threads to terminate.

isAlive(): The isAlive() method checks whether a thread is still executing.

getName(): The getName() method returns the name of a thread.

setName(): The setName() method sets the name of a thread.
quietin
2016-01-03 11:14:24 +08:00
@boyhailong 可以是可以,但是手动设置 name 感觉不是很好

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/247520

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX