c++辅助python实现多线程(条件变量)

程序很简单,主要是熟悉一下c++和python的编程,然后那个条件变量的使用花了点时间,主要是以前没用过.

主要用途想以后建立个线程池非阻塞的调用sql.

#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include "Python.h"

//加载时初始化和卸载时清理
void __attribute__ ((constructor)) my_init(void);
void my_fini(void) __attribute__((destructor));
#define GIGNAL_BEGIN (SIGUSR1+1)
#define GIGNAL_FINISH (SIGUSR1+2)

pid_t pid;
int value;
int is_begin = 0, is_end = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func(void *args)
{
    int *r = args, i = 0;
    printf("in func");
    while(1)
    {
        pthread_mutex_lock(&mutex);
        while(!is_begin)
        {
             pthread_cond_wait(&cond, &mutex);
        }
        is_begin = 0;
        pthread_mutex_unlock(&mutex);
        *r = i++;
        pthread_mutex_lock(&mutex);
        is_end = 1;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
    return (void *)0;
}


void my_init(void)
{
    int err;
    if((err = pthread_create(&pid, NULL, func, &value)) != 0)
    {
        printf("errno=%d\n",err);
    }
    pthread_mutex_init(&mutex, NULL);
    return;
}

int increase()
{
    pthread_mutex_lock(&mutex);
    is_begin = 1;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&mutex);
    while(!is_end)
    {
        pthread_cond_wait(&cond, &mutex);
    }
    is_end = 0;
    pthread_mutex_unlock(&mutex);
    return value;
}

static PyObject* wrap_increase(PyObject *self, PyObject *args)
{

    int result = increase();
    //把得到的结果包装成Python对象,并返回

    return (PyObject*)Py_BuildValue("i", result);
}

void my_fini(void)
{
    pthread_mutex_destroy(&mutex);
    return;
}

int add(int arg1, int arg2)
{
    return arg1 + arg2;
}

static PyObject* wrap_add(PyObject *self, PyObject *args)
{
    //把输入的Python对象转换为C/C++能识别的数据

    int arg1, arg2;
    if(!PyArg_ParseTuple(args, "ii", &arg1, &arg2))
    return NULL;
    //调用C/C++函数,得到结果

    int result = add(arg1,arg2);
    //把得到的结果包装成Python对象,并返回

    return (PyObject*)Py_BuildValue("i", result);
}



static PyMethodDef wrap_methods[] ={
    {"add", wrap_add, METH_VARARGS, "求和"}, //函数名(调用),函数地址,参数类型,函数说明
    {"increase", wrap_increase, METH_VARARGS, "求和"},
    {NULL, NULL}
};

//入口看书,init后必须跟模块的名字
void initwrap (void)
{
    Py_InitModule("wrap", wrap_methods);
}

你可能感兴趣的:(python)