如何将多个参数传递给c中的线程? [分段故障]

时间:2017-10-17 13:32:46

标签: c multithreading pthreads

我试过按照几个答案/ tuturials的程序,我仍然在将多个参数传递给一个线程时出现分段错误?我做错了什么?

结构:

struct client_struct {
    int socketId;
    char *message;
};

过程功能:

// Handle socket session
void *process(void *client)
{
    client_struct *tmpClient = (client_struct*)client;
    char sendline[BUFFSIZE], recvline[BUFFSIZE];
    printf("can't reach this: %i\n", tmpClient->socketId);
    strncpy(sendline, tmpClient->message, sizeof(sendline)-1);
    sendline[sizeof(sendline)-1] = '\0';
}

从main调用:

int sendMessage(const char *message, int sock)
{
    int result;
    pthread_t process_thread;

    struct client_struct * client;
    client->socketId = sock;
    strcpy(client->message, message);
    printf("segmentation fault here: %s\n", client->message);

    pthread_create(&process_thread, NULL, process, client);
    pthread_detach(process_thread);
}

2 个答案:

答案 0 :(得分:1)

未初始化指针时未定义行为的经典问题。

struct client_struct * client;

client = malloc(sizeof(*client)); //Allocate memory for client
client->... = ...; //DO you job

通过执行struct client_struct * client;,您只会声明变量(可能在某个时刻)指向struct client_struct类型的数据。由于您还没有数据,因此取消引用未初始化的指针会导致未定义的行为。

使用malloc,您正在为指针设置有效数据。

答案 1 :(得分:0)

也可以使用简单的proxyargs结构:

var results = customer.Where(c => c.Reports.Any())
                      .SelectMany(c => {c, c.Reports.Max(r => r.Created)})
                      .ToList();