gpt4 book ai didi

c - Helgrind报告单线程上的数据争用

转载 作者:行者123 更新时间:2023-12-03 12:55:23 24 4
gpt4 key购买 nike

当试图创建一个仅读取并打印自己的参数然后返回的单个线程时,尽管主线程在创建新线程后立即执行pthread_join的事实,但是helgrind会发现很多可能的数据竞争。

这是线程初始化(缩小后的版本仍会重现该问题):

void liveness(cfg_t* cfg)
{
vertex_t* u;
size_t i;
size_t* arg;
pthread_t thread;
pthread_mutex_t* lock;

lock = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
if (lock == NULL) {
printf("Error when allocating memory for locks");
}
if (pthread_mutex_init(lock, NULL) != 0) {
printf("Error when creating lock\n");
}

arg = malloc(sizeof(size_t));
(*arg) = 0;
if (pthread_create(&thread, NULL, thread_start, arg)) {
perror("Error when creating thread\n");
exit(1);
}
if (pthread_join(thread, NULL)) {
perror("Error when joining thread\n");
exit(1);
}
free(lock);
free(arg); //244
}

这是thread_start
void* thread_start(void* arguments)
{
size_t index;
index = * (size_t*) arguments; /155
printf("Thread started! Index %zu\n", index);
fflush(stdout);
return NULL;
}

输出正确(线程已启动!索引0),但是helgrind产生以下输出
==3489== Possible data race during write of size 8 at 0x4003330 by thread #1
==3489== Locks held: none
==3489== at 0x42970F: _int_free (in /h/d9/b/dat11ote/courses/edan25/lab4home/live)
==3489== by 0x402D5C: liveness (paralleldataflow.c:244)
==3489== by 0x401E4F: main (main.c:134)
==3489==
==3489== This conflicts with a previous read of size 8 by thread #2
==3489== Locks held: none
==3489== at 0x402C4C: thread_start (paralleldataflow.c:155)
==3489== by 0x4040B1: start_thread (pthread_create.c:312)
==3489== by 0x4500E8: clone (in /h/d9/b/dat11ote/courses/edan25/lab4home/live)

和另外25个上下文中的30个错误。如果我将return语句更改为在线程参数之前,如
void* thread_start(void* arguments)
{
size_t index;
return NULL;
}

然后一切正常。我将-pthreads和-static标志用于gcc。如果删除了printf和fflush,这将导致上面的错误,但会删除所有其他错误,如下所示:
Possible data race during write of size 8 at 0x6D7878 by thread #1
Locks held: none
at 0x40F449: vfprintf (in /h/../live)
by 0x419075: printf (in /h/../live)
by 0x401E76: main (main.c:137)
This conflicts with a previous write of size 8 by thread #2
Locks held: none
at 0x40F449: vfprintf (in /h/../live)
by 0x419075: printf (in /h/../live)
by 0x402C68: thread_start (in /h/../live)
by 0x404061: start_thread (pthread_create.c:312)
by 0x44B2A8: clone (in /h/../live)

最佳答案

如果使用-static链接,则表示valgrind/helgrind
无法替换或包装必须替换/包装的一组功能
使海格格朗德(Helgrind)正常工作。

通常,要使helgrind正常工作,请使用诸如malloc/free/...之类的功能。
必须更换。
诸如pthread_create/pthread_join/...之类的函数必须由helgrind包装。

使用静态库意味着这些函数不会被替换或包装,
造成很多误报。

关于c - Helgrind报告单线程上的数据争用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32760669/

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