2011-12-31 100 views
0

出於某種原因,pthread_create不允許我將struct作爲參數。這個問題與系統無關,儘管我沒有機會在其他人的盒子上測試它。由於某種原因,我根本不允許我通過struct;它返回錯誤#12。爲什麼pthread_create()返回12?

問題不在於內存。我知道12是ENOMEM,「應該是那個」,但它不是......它根本不會接受我的結構作爲指針。

struct mystruct info;  
info.website = website; 
info.file = file; 
info.type = type; 
info.timez = timez; 
for(threadid = 0; threadid < thread_c; threadid++) 
    { 
    // printf("Creating #%ld..\n", threadid); 
    retcode = pthread_create(&threads[threadid], NULL, getstuff, (void *) &info); 
    //void * getstuff(void *threadid); 

當我在GDB運行這段代碼,因爲某些原因,它沒有返回碼12 ..但是,當我在命令行中運行它,它會返回12

任何想法?在Linux上

+0

線程例程'getstuff()'的參數是'&info'的指針,它不是一個線程ID,儘管你的註釋是它的參數是'threadid'。你可能知道這一點,但只是雙重檢查。 – 2011-12-31 04:16:51

+0

假設你傳遞一個空指針而不是'info'的地址;你可以把'info'變成一個全局變量,因爲線程都使用相同的信息 - 只是不要在任何線程中修改它。你還會遇到內存問題嗎?你有沒有將任何文件或共享內存段映射到任何地方?你正在使用32位還是64位平臺(編譯)?你有沒有嘗試爲'pthread_create()'的第二個參數創建一些線程屬性? – 2011-12-31 04:21:12

回答

6

錯誤代碼12:

#define ENOMEM   12  /* Out of memory */ 

你很可能運行內存。確保你沒有分配太多的線程,並且一定要在線程完成時(或使用pthread_detachpthread_join線程。確保你沒有通過其他方式耗盡你的記憶。

+0

未釋放malloc()..謝謝,我沒有調試我的線程。 – Saustin 2011-12-31 04:18:54

2

將堆棧對象作爲參數傳遞給pthread_create是一個非常糟糕的主意,我將它分配到堆上。錯誤12是ENOMEM。

+0

我試着用malloc分配它,但它仍然返回12;在對指針使用正確的修改之後,它仍然具有相同的效果..它像它只接受類型爲long的ptrs – Saustin 2011-12-31 04:06:41

1

嘗試添加一些適當的錯誤處理。

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 
static void fail(const char *what, int code) 
{ 
    fprintf(stderr, "%s: %s\n", what, strerror(code)); 
    abort(); 
} 

... 
if (retcode) 
    fail("pthread_create", retcode); 

在我的系統上,12是ENOMEM(內存不足)。