gpt4 book ai didi

c - 将指针传递给新线程的堆栈变量 - 这段代码安全吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:53 25 4
gpt4 key购买 nike

考虑以下代码:

void* echo_data(void* client_socket) {
// for the sake of argument - suppose there's a lot of code here before we copy the socket to local variable:
int socket = *(int*)client_socket;
// send back whatever is coming from client
return (void*)0;
}

int main(int argc, char* argv[]) {
int server_socket = establish_connection();

while (1) {
int incoming_client_socket = wait_for_connection(server_socket);
fprintf(stdout, "new connection accepted...\n");

pthread_t client_thread;
pthread_create(&client_thread, NULL, echo_data, (void*)&incoming_client_socket);
}
}

我知道我在这里忽略了返回码,但这段代码实际上并没有运行(没有 establish_connectionwait_for_connection)并且放在一起是为了传达一个想法,所以为了争论起见,我们假设所有函数总是成功......
但是,我确实特别想知道使用局部变量作为新创建线程的参数的含义。
考虑以下场景:

  1. wait_for_connection 接受新连接并返回 incoming_client_socket
  2. incoming_client_socket 在新创建的线程中“通过引用”传递给 echo_data,而它当前存储在 main() 的卡住了。
  3. 现在假设 echo_data 复制了 client_socket 指向的数据需要一些时间,与此同时,主线程接受另一个连接,这将超越前一个incoming_client_socket - 然后线程复制了错误的数据。

这是一个真正的问题吗?如果不是,怎么会呢?如果是这样,这样做的安全方法是什么?

最佳答案

Is that a real concern?

是的。这不是一种安全的方式。

您可以直接传递值而不是传递其地址。

pthread_create(&client_thread, NULL, echo_data, (void*) incoming_client_socket);`

线程函数应该是这样的

void* echo_data(void* client_socket) {
int socket = (int)client_socket;
/* your code */
}

如果您希望将多个元素传递给线程,那么您可以将其包装在一个结构中,为它创建一个结构指针,分配内存并填充值并将指针传递给线程。

struct X {
int socket;
/* other members here*/
};

  while (1) {
int incoming_client_socket = wait_for_connection(server_socket);
fprintf(stdout, "new connection accepted...\n");
struct X *ptr = malloc (sizeof(struct X));
ptr->socket = incoming_client_socket;
/* other assignment here */

pthread_create(&client_thread, NULL, echo_data, (void*)ptr);
}

你的线程函数应该是这样的

void* echo_data(void* client_socket) {
// for the sake of argument - suppose there's a lot of code here before we copy the socket to local variable:
struct X *ptr = (struct X *)client_socket;
// send back whatever is coming from client
return (void*)0;
}

不要忘记释放内存。

关于c - 将指针传递给新线程的堆栈变量 - 这段代码安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com