重复构建和销毁上下文会报错 #1260

repeatedly construct and destroy context gives an error #1260

在我的项目下,需要反复构造和销毁context却报错

例如:

import zmq

for i in range(100):
    print(i)
    context = zmq.Context()
    data_socket = context.socket(zmq.SUB)
    data_socket.connect("tcp://127.0.0.1:5552")
    data_socket.setsockopt_string(zmq.SUBSCRIBE, "")
    context.destroy()

它returns

0
1
2
3
4
5
6
7
8
9
10
11
12
13
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    data_socket.connect("tcp://127.0.0.1:5552")
  File "zmq/backend/cython/socket.pyx", line 580, in zmq.backend.cython.socket.Socket.connect
  File "zmq/backend/cython/checkrc.pxd", line 25, in zmq.backend.cython.checkrc._check_rc
zmq.error.ZMQError: Socket operation on non-socket

套接字选项必须放在.connect().bind()方法之前,您可以从zmq.Context().

创建单元实例

试一试:

import zmq

context = zmq.Context.instance()

for i in range(100):
    print(i)
    data_socket = context.socket(zmq.SUB)
    data_socket.setsockopt(zmq.SUBSCRIBE, b"")
    data_socket.connect("tcp://127.0.0.1:5552")

context.destroy()

[你的答案]:

但是,如果您想按照自己的方式进行操作,则应在每次迭代中关闭套接字,因此您的代码片段将为:

import zmq

for i in range(100):
    ctx = zmq.Context.instance()
    sock = ctx.socket(zmq.SUB)
    sock.setsockopt(zmq.SUBSCRIBE, b'')
    sock.connect('tcp://127.0.0.1:5552')
    sock.close()  # Note
    ctx.destroy()
    print('ctx closed status: ', ctx.closed, ' iteration: ', i)

输出:

('ctx closed status: ', True, ' iteration: ', 0)
('ctx closed status: ', True, ' iteration: ', 1)
('ctx closed status: ', True, ' iteration: ', 2)
('ctx closed status: ', True, ' iteration: ', 3)
('ctx closed status: ', True, ' iteration: ', 4)
('ctx closed status: ', True, ' iteration: ', 5)
('ctx closed status: ', True, ' iteration: ', 6)
('ctx closed status: ', True, ' iteration: ', 7)
('ctx closed status: ', True, ' iteration: ', 8)
('ctx closed status: ', True, ' iteration: ', 9)
('ctx closed status: ', True, ' iteration: ', 10)
('ctx closed status: ', True, ' iteration: ', 11)
('ctx closed status: ', True, ' iteration: ', 12)
('ctx closed status: ', True, ' iteration: ', 13)
('ctx closed status: ', True, ' iteration: ', 14)
.
.
.