2014-07-24 26 views
0

我正在學習多線程的概念,並且遇到了使用信號量互斥鎖的問題。使用POSIX線程的文件操作

這裏是我的代碼片段:

void *thread1_funct(void * myfileptr) 
{ 
static int count; 
printf("\nThread1 ID:%u\n",(unsigned int) pthread_self()); 
printf("\nThread1 function, file pointer received:0x%x\n", (FILE*)myfileptr); 

for (;;) 
{ 
count++; 
sem_wait(&mutex); 
fprintf(myfileptr, "%d\n", count); 
sem_post(&mutex); 
} 

return NULL; 
} 


void *thread2_funct(void *myfileptr) 
{ 
static int count=0; 

printf("\nThread2 ID:%u\n",(unsigned int) pthread_self()); 
printf("\nThread2 function, file pointer received:0x%x\n", (FILE*)myfileptr); 

for (;;) 
{sem_wait(&mutex); 
fscanf(myfileptr, "%d\n", &count); 
printf("\n......%d......\n", count); 
sem_post(&mutex); 
} 

return NULL; 
} 

兩個線程我已經建立。一個將dfata寫入一個文件,另一個將讀取最新的數據。

這是我的主要方法:

int main(int argc, char **argv) 
{ 
FILE *fileptr = fopen(*(argv+1), "a+"); 

sem_init(&mutex, 0x00, 0x01); 

if ((thread1_ret = pthread_create(&thread1, NULL, thread1_funct, (void*)fileptr)) == 0) 
printf("\nThread1 created successfully....\n"); 
else 
printf("\nFailed to create Thread1\n"); 

if ((thread2_ret = pthread_create(&thread2, NULL, thread2_funct, (void*)fileptr)) == 0) 
printf("\nThread2 created successfully....\n"); 
else 
printf("\nFailed to create Thread2\n"); 

pthread_join(thread1, NULL);         
pthread_join(thread2, NULL);         

fclose(fileptr); 

sem_destroy(&mutex); 

pthread_exit(NULL); 
return 0; 
} 

預期輸出是: ........ 1 ........ ........ 2 ........ ........ 3 ........

等......直到程序手動中斷。

但我的輸出全部爲0: ........ 0 ....... ........ 0 ....... .... .... 0 ....... ........ 0 .......

等等....

請幫助我。我哪裏錯了?

+0

我建議使用名稱'互斥量'作爲信號量可能會令人困惑 - 在這種情況下,您應該可能使用'互斥量',而不是信號量(不是因爲信號量「但是 - 這只是一個比你需要的更大的錘子)。另外@Gyycon在文件指針位置下面的答案很可能是因爲緩衝數據永遠不會被寫出來 - 至少在一段時間內...... – twalberg

+0

每次寫入或使用unbuffer I/O,即'open()','write()','read()'和'close()'以及兩個文件描述符。 – alk

回答

1

線程1寫入文件,並將文件指針前進 - 文件末尾。線程2從指向文件末尾的文件指針中讀取,所以你什麼也得不到。

您可以使用fseek,或者在線程2中回滾以獲取數據。

+0

...或pread()進入一個緩衝區,然後用sscanf(),strtol()等進行解析...雖然你必須查詢底層的FILE *文件描述符第一.. – twalberg

+0

無論我使用倒帶或fseek不會我仍然會一遍又一遍地循環相同的數據? – shre3841279

+0

你將不得不計算文件的大小,然後尋求EOF - sizeof(你的記錄)。爲什麼不爲寫作者和讀者線程使用不同的文件指針? – Greycon