'Can I use a `multiprocessing.Queue` for communication within a process?
I'm using queues for inter-thread communication. I'm using multiprocessing.Queue() instead of queue.Queue() because the multiprocessing version exposes an underlying file descriptor which can be waited on with select.select - which means I can block waiting for an object in the queue or a packet to arrive on a network interface from the same thread.
But when I try to get an object from the queue, I get this:
Traceback (most recent call last):
File "/usr/lib/python3.6/multiprocessing/queues.py", line 234, in _feed
obj = _ForkingPickler.dumps(obj)
File "/usr/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: can't pickle _thread.lock objects
Is there a way to do this? Or am I stuck using queue.Queue() and having a separate thread select.select() on the sockets and put the results into the queue?
Edit: I think this is the minimal reproducible example:
import multiprocessing
import threading
queue = multiprocessing.Queue()
class Msg():
def __init__(self):
self.lock = threading.Lock()
def source():
queue.put(Msg())
def sink():
obj = queue.get()
print("Got")
threading.Thread(target=sink).start()
source()
The problem is that the object I'm putting into the queue has a threading.Lock object as a field (at several levels of composition deep).
Solution 1:[1]
you should add scanner.nextLine(); in your catch block
the explenation is that you need to clear the scanner and to do so you should use nextLine()
" To clear the Scanner and to use it again without destroying it, we can use the nextLine() method of the Scanner class, which scans the current line and then sets the Scanner to the next line to perform any other operations on the new line."
for more understanding visits the link
your code will look like this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0;
boolean success = false;
System.out.println("Enter an int numbers :");
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
scanner.nextLine();
}
}
System.out.println(i);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
