Question

I was looking how to do a multithread (2 threads) in python.

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...

How do I declare a shared variable in python? or it is just another variable....

No correct solution

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top