2015-09-24 78 views
1

當試圖創建一個只讀取並打印自己的參數然後返回的單個線程時,儘管主線程儘快執行了pthread_join,但helgrind發現了很多可能的數據競爭新的線程被創建。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個錯誤EXTS。如果我改變返回語句去線程參數之前,如在

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) 
+0

「鎖定」互斥鎖的目的是什麼? –

+0

截至目前,什麼都沒有,儘管我希望在線程按預期工作時(以前它是作爲結構的一部分與其他參數一起傳遞的,以及其中有幾個線程)傳遞的。我嘗試完全刪除對它的引用,但它不能解決任何問題。 – OlleTO

+0

如果您從線程回調註釋掉庫函數會發生什麼情況? printf和fflush。 – Lundin

回答

2

如果你用-static鏈接,那麼就意味着的valgrind/helgrind 不能取代或包裝一套必須更換/包裝的功能,以使helgrind正常工作。

通常,要使helgrind正常工作,必須更換malloc/free/... 等函數。 函數,如pthread_create/pthread_join/...必須由helgrind包裝。

使用靜態庫意味着這些函數不會被替換或包裝,導致大量的誤報。