简体   繁体   English

在python中暂停一个线程

[英]Pause one thread from other in python

I was looking how to do a multithread (2 threads) in python. 我一直在寻找如何在python中执行多线程(2个线程)。

I want one of them is reading the serial port constantly. 我希望其中之一正在不断读取串行端口。 reading every frame and saving them to a database. 读取每帧并将其保存到数据库。 I already have done a script to do this. 我已经做了一个脚本来做到这一点。

For the second one, I want it to listen a socket port. 对于第二个,我希望它监听一个套接字端口。 When it receives something from that port, I want it to pause the first thread, write something to the serial port and write to the socket. 当它从该端口接收到某些内容时,我希望它暂停第一个线程,将一些内容写入串行端口并写入套接字。 After that, unpause the first thread and go back to listen socket port. 之后,取消暂停第一个线程,然后返回以监听套接字端口。

I think the best idea is pausing one thread from the other to read serial port in that moment because if I read the answer by serial port in the 1th thread, I have to pass value read to the second one and it is more complicated, isn't it? 我认为最好的主意是在那一刻暂停另一个线程读取串行端口,因为如果我在第一个线程中通过串行端口读取答案,则必须将值读给第二个线程,这更复杂了,是不是吗

I already have the part of writing on serial port and check some tutorials for socket part so I have no problems with that. 我已经在串行端口上进行了编写,并查看了一些有关套接字部分的教程,因此我对此没有任何问题。 But I haven't find anything about pause one thread from another and I am thinking it is not possible. 但是我没有找到任何关于暂停另一个线程的信息,我认为这是不可能的。

What should I do in this case? 在这种情况下我该怎么办?

EDIT: Ask about shared variables: SO I can declare a global variable and make something like: 编辑:询问共享变量:所以我可以声明一个全局变量,使像:

global1
global2
Thread 1:

while(global1 == 0)
    do whatever
global2 = 1

thread 2:
    wait socket
    if dataReceived: global1 = 1
    if global2 = 1 do whatever on serial port
    global2 = 0
    when finish global1 = 0

with 2 globals I can notify to thread1 to stop to go ahead next iteration and with global2, the second thread knows when the serial port is not being used... 使用2个全局变量,我可以通知线程1停止继续进行下一次迭代,而使用global2,第二个线程知道何时不使用串行端口...

How do I declare a shared variable in python? 如何在python中声明共享变量? or it is just another variable.... 还是只是另一个变量...

I'm not sure you can share objects directly between processes, but since every process can share objects with the main process, you can use the main process to pass them back and forth: 我不确定您是否可以在进程之间直接共享对象,但是由于每个进程都可以与主进程共享对象,因此可以使用主进程来回传递它们:

http://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes http://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM