小编pou*_*ill的帖子

Python GIL和线程

我已经在大型C ++应用程序中嵌入了Python3。Python提供了用于自定义数据处理的用户脚本功能。
问题:我有许多与Python交互的线程,但是我真的不知道如何使用GIL保护我的代码。到目前为止,使代码工作的唯一方法是使用boost::mutex

这是一个非常简化的示例,重现了我的问题:

  • 线程A首先调用Init()以初始化Python(静态函数)。
  • 线程B调用Pythonize()在Python上做一些工作。第一次锁定GIL时,线程B被阻塞。

代码

#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include "Python.h"

struct RTMaps_GILLock
{
    RTMaps_GILLock()
    {
        std::cout << "Locking..." << std::endl;
        m_state = PyGILState_Ensure();
    }

    ~RTMaps_GILLock()
    {
        std::cout << "Unlocking..." << std::endl;
        PyGILState_Release(m_state);
    }

private:
    PyGILState_STATE m_state;
};
#define GILLOCK RTMaps_GILLock lock;

class PythonEmbed
{
public:
    static void Init()
    {
        Py_Initialize();
        // EDIT : adding those two lines made my day :
        PyEval_InitThreads(); // This acquires GIL
        PyEval_SaveThread(); …
Run Code Online (Sandbox Code Playgroud)

c++ python-c-api gil python-3.x

5
推荐指数
1
解决办法
1090
查看次数

使用 Boost.Asio 将 UDP 套接字绑定到特定网络接口

我的电脑有多个网卡,我正在尝试从多个广播设备接收 UDP 数据。每个设备都隔离在专用网络上,我尝试同时从多个设备读取 UDP 数据。我使用的是 Boost 1.67 版本。让我们在这篇文章中假设我只想从一个特定设备获取数据,因此我想绑定到本地网络接口。

在 Windows 上,以下代码可以工作,但在我的 Ubuntu 16.04 64 位机器上却不能。事实上,如果我绑定到一个特定的本地 IP 地址(本例中为 192.168.1.1),我不会获得任何数据。但如果我使用任何“0.0.0.0”地址,那么我就会得到我想要的。但在那种情况下我不知道它来自哪里。任何网卡都可以接收!

这是正常行为吗?或者我是否需要阅读sender_endpointLinux 上的信息才能了解这些信息并随后进行过滤?

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

int main(int argc, char* argv[])
{
  try
  {
    boost::asio::io_context io_context;

    // Setup UDP Socket
    udp::socket socket(io_context);
    socket.open(udp::v4());

    // Bind to specific network card and chosen port
    socket.bind(udp::endpoint(boost::asio::ip::address::from_string("192.168.1.1"), 2368));

    // Prepare to receive data
    boost::array<char, 128> recv_buf;
    udp::endpoint sender_endpoint;
    size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);

    // Write data to std output
    std::cout.write(recv_buf.data(), …
Run Code Online (Sandbox Code Playgroud)

c++ sockets boost boost-asio

5
推荐指数
1
解决办法
2934
查看次数

标签 统计

c++ ×2

boost ×1

boost-asio ×1

gil ×1

python-3.x ×1

python-c-api ×1

sockets ×1