gpt4 book ai didi

c - 从 while 循环将值传递到线程

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

我有一个 while 循环,它获取一个值并使用该信息在新线程中调用一个函数。问题是我无法让它在 while 循环的每次迭代中为该信息提供一个新地址。所以 while 循环最终会修改正在运行的线程所使用的信息。

这是我的代码的摘录。 printf 语句显示 string 的地址相同,因此在线程运行时被覆盖

    char * string = (char *) malloc(1024 * sizeof(char));
strcpy(string, item);
if (pthread_create(&thread, NULL, printWithDelay, &string)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
printf("Dispatched thread for %s at %p\n", string, &string);
free(string);

我也尝试过不使用 malloc,但那也行不通。有什么办法吗?

在你问之前,是的,我是一名学生,是的,这是一项作业。但是,任务并没有要求我做任何这些。我们甚至不应该知道线程的存在。我只是想强制自己超越作业的范围,但遇到了一些麻烦。我想把 sleepsort 作为一个我认识的评分员的笑话。

完整代码和任务描述在这里:http://hastebin.com/cetepakevu.c

最佳答案

在你当前的 pthread_create 调用中,你有一个竞争条件,因为你传递的是 &string 而不是 string (即你传递的是指向主线程的 string 变量而不是它的 contents 的指针。因此,两个 [或更多] 子线程最终可能会使用相同的字符串缓冲区。

此外,您还让主线程对字符串执行 free 操作。这必须在子线程中完成。 free 全局适用于所有线程,因此 main 在 child 可以使用数据之前执行 free [或此后不久将其从自身下面拉出]。

此外,还有一个由此产生的“小”问题:因为 main 执行了 mallocfree [假设没有 child 线程执行任何 malloc],很可能 malloc 将始终返回相同的值。因此,无论是否存在竞争条件,所有子线程都可以使用相同的字符串缓冲区。

另一方面,如果一个子线程为其他事情做了一个malloc,它现在正在与使用string[已经分配但释放]和新分配。因此,如果以“正确”的方式写入两个区域中的任何一个,则持有/使用 string 的先前值的人可能会导致堆损坏 [和/或段错误],因为 malloc/heap 链接指针可能位于重叠的不同分配的中间。


这是我认为你有的[因为你没有显示子函数]:

void
main_thread(void)
{

while (1) {
char *string = (char *) malloc(1024 * sizeof(char));

strcpy(string, item);

// BUG: race condition -- on the second loop, string can be changed
// before thread 1 has a chance to dereference it, so thread 1
// could end up using thread 2's string (or thread 3's ...)
if (pthread_create(&thread, NULL, printWithDelay, &string)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}

// BUG: child must do the free
printf("Dispatched thread for %s at %p\n", string, &string);
free(string);
}
}

void *
printWithDelay(void *arg)
{
char **strptr = arg;
char *string;

// BUG: this is the race condition -- we can get our string or
// if we're delayed, we'll get the string for the next thread, so
// we'd both use the same address
string = *strptr;

// use string ...

return (void *) 0;
}

修改后的代码:

void
main_thread(void)
{

while (1) {
char *string = (char *) malloc(1024 * sizeof(char));

strcpy(string, item);

if (pthread_create(&thread, NULL, printWithDelay, string)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
}
}

void *
printWithDelay(void *arg)
{
char *string = arg;

// use string ...

free(string);

return (void *) 0;
}

关于c - 从 while 循环将值传递到线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37266713/

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