I’m using swiplserver and my aim is to control it in some multiprocessing application in python. My application loads some .pl file (say test.pl) and so it costs much time to init the server every time in the loop with e.g.:
with PrologMQI() as mqi:
with mqi.create_thread() as prolog_thread:
prolog_thread.query(f"consult('{PL_TEST}').")
result = prolog_thread.query("test().")
print(result)
My Idea now is to initiate the server only once (see function ‘get_new_prolog’) at the start of the process or alternative at the start of the program itself. Here is some code example of my problem (here I start the server once at start of every process):
Prolog file (test.pl):
test():-
false.
Python file:
import multiprocessing
from config import *
from pathlib import Path
from swiplserver import PrologMQI, json_to_prolog
ROOT_DIR = Path(__file__).parent.parent
PL_TEST = f"{ROOT_DIR}/prolog/test.pl"
def get_new_prolog():
MQI = PrologMQI()
MQI.start()
PL = MQI.create_thread()
PL.start()
PL.query(f"consult('{PL_TEST}').")
return PL
def find(process, initial, PL ):
succ = False
i = 0
print(f"Init: {process}")
while i < 50:
# with PrologMQI() as mqi:
# with mqi.create_thread() as prolog_thread:
# prolog_thread.query(f"consult('{PL_TEST}').")
# result = prolog_thread.query("test().")
# print(result)
PL.query(f"test().")
i = i + 1
threads = []
PL = get_new_prolog()
processes = []
manager = multiprocessing.Manager()
queue = multiprocessing.Queue(maxsize=1)
for i in range(2):
process = multiprocessing.Process(target=find, args=(f'computer_{i}', i, PL))
processes.append(process)
process.start()
ret = queue.get()
for i in range(2):
process = processes[i]
process.terminate()
print(f'terminated {i}')
print(ret)
If I execute this I get the error:
File "/usr/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/lib/python3.9/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/home/martin/Dokumente/Programme/git/my/Beginning-Logic/python/test.py", line 29, in find
PL.query(f"test().")
File "/home/martin/.local/lib/python3.9/site-packages/swiplserver/prologmqi.py", line 682, in query
return self._return_prolog_response()
File "/home/martin/.local/lib/python3.9/site-packages/swiplserver/prologmqi.py", line 831, in _return_prolog_response
raise {
swiplserver.prologmqi.PrologError: unknownCommand
As solution I could uncomment the lines
# with PrologMQI() as mqi:
# with mqi.create_thread() as prolog_thread:
# prolog_thread.query(f"consult('{PL_TEST}').")
# result = prolog_thread.query("test().")
# print(result)
and comment the following line
PL.query(f"test().")
but this costs a lot of time. Is their a way to:
- Get a quick execution time
- Solve the error above?