从pthread_create将多个参数传递给线程函数

Chr*_*ard 7 c posix pthreads

这是我在C中进行线程化的第一次尝试.我正在创建一个循环有界的缓冲区.我知道如何创建线程,但我看到的所有示例都只有接受一个void参数的线程函数,但不幸的是我的工作者规范要求我使用三个,如下所示:

void bufferRead(BoundedBuffer* buffer, char* data, int count) {
    pthread_mutex_lock(&buffer->mutexBuffer);
    <snip>
    pthread_mutex_unlock(&buffer->mutexBuffer);
}
Run Code Online (Sandbox Code Playgroud)

这是我的pthread_create语句

pthread_create(&buffer.readThread, NULL, (void *)bufferRead, &readParams)
Run Code Online (Sandbox Code Playgroud)

和我的readParams结构/赋值

struct readThreadParams {                                                   
    BoundedBuffer b;                                                        
    char* data;                                                             
    int count;                                                              
};                                                                          

struct readThreadParams readParams;                                         
readParams.b = buffer2;                                                     
readParams.data = out_array;                                                
readParams.count = in_size;
Run Code Online (Sandbox Code Playgroud)

关于如何在传递给bufferRead函数之后分配每个struct的参数的任何建议将不胜感激.

Dan*_*tos 8

那是因为你只需要一个参数.当我们有多个值时(通常就是这种情况),我们将其封装到结构中.pthread_create将调用的函数类型是不可协商的.这是一个区域,你的函数指针的类型转换会让你陷入严重的麻烦.

#include <pthread.h>
#include <stdlib.h>

struct BoundedBuffer {
    pthread_t readThread;
    pthread_mutex_t mutexBuffer;
} buffer2;

struct readThreadParams {
    struct BoundedBuffer b;
    char* data;
    int count;
};

void *bufferRead (void *context) {
    struct readThreadParams *readParams = context;

    pthread_mutex_lock(&readParams->b.mutexBuffer);
    //<snip>
    pthread_mutex_unlock(&readParams->b.mutexBuffer);

    return NULL;
}

int main(void) {
    int ret;
    char *out_array = malloc(42);
    size_t in_size = 42;

    struct readThreadParams readParams;
    readParams.b = buffer2;
    readParams.data = out_array;
    readParams.count = in_size;

    /* I presume that by "buffer", you really meant the .b member of
     * struct readThreadParams.  Further, this must have a member
     * named readThread of type pthread_t, etc.
     */
    ret = pthread_create(&readParams.b.readThread, NULL, bufferRead, &readParams);

    if (!ret) {
        pthread_join(&readParams.b.readThread, NULL);
    }

    free(out_array);

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

  • -1将局部变量传递给另一个线程 (5认同)