繁体   English   中英

在C ++中使用pthread

[英]Using pthreads in C++

我需要在C ++中使用pthreads,但是我不能使用pthread_create函数,它向我显示了一个错误。 另外,我需要将多个参数传递给方法:

void Read(int socks, int client) {
    while (1) {
        int n;
        char buffer1[256];
        bzero(buffer1, 256);
        n = read(socks, buffer1, 255);
        if (n < 0) {
            perror("ERROR leyendo el socket");
            exit(1);
        }
        cout << "Mensaje de cliente " << client << ":" << buffer1 << endl;
        Jsons json1;
        json1.parseJson(buffer1);
        writeMsg(socks, "hola\n");
    }

}

void ThreadServer::Thread(int sock, int client) {

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_t tid;
    pthread_create(&tid,&attr,Read);

}

如果我理解正确,则希望将多个参数发送到线程。 pthread的线程函数使用单个void *

void threadfn(void *data);

您只需要创建一个数据结构来保存您的参数

 struct threadData
 {
     int param1;
     int param2;
 };

声明您的结构并分配参数值。 调用pthread_create ,传递struct指针。

struct threadData data = {1,2};

pthread_create(&tid, &attr, Read, &data);

当您在读取函数中获得指针时,强制转换并使用它来提取参数。

void Read( void * thrData) 
{
    struct threadData *myParams = (struct threadData*)thrData;
    .
    .
    .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM