我有以下简单程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>
#include <errno.h>
#define handle_error_en(en, msg) \
{do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0);}
#define status_check(stat) ((stat != 0) ? (handle_error_en(stat, "status error")) : ((void)0))
static void* thread_start(void *arg)
{
printf("%s\n", "thread working..");
sleep(1);
return NULL;
}
int main(int argc, char const *argv[])
{
int status;
pthread_t thread;
status = pthread_create(&thread,
NULL,
thread_start,
NULL);
status_check(status);
status = pthread_join(thread, NULL);
status_check(status);
printf("%s\n", "exit program..");
return 0;
}
当我用
运行Valgind时Valgrind --tool=helgrind ./threads_simple
我得到54个错误,都是数据争用错误。只选择其中一个:
Possible data race during write of size 4 at 0x1003FD2D8 by thread #1
==17334== Locks held: none
==17334== at 0x1003E2FDF: spin_unlock (in /usr/lib/system/libsystem_platform.dylib)
==17334== by 0x1003F7EAF: pthread_join (in /usr/lib/system/libsystem_pthread.dylib)
==17334== by 0x100000E37: main (threads_simple.c:29)
==17334==
==17334== This conflicts with a previous write of size 4 by thread #2
==17334== Locks held: none
==17334== at 0x1003E2FDF: spin_unlock (in /usr/lib/system/libsystem_platform.dylib)
==17334== by 0x1003F6FD6: _pthread_start (in /usr/lib/system/libsystem_pthread.dylib)
==17334== by 0x1003F43EC: thread_start (in /usr/lib/system/libsystem_pthread.dylib)
==17334== Address 0x1003fd2d8 is in the Data segment of /usr/lib/system/libsystem_pthread.dylib
我写了更多小的线程程序,都给出了这样的错误。我的Valgrind安装是否已损坏?我通过brew安装在Mac上。