我正在學習多線程的概念,並且遇到了使用信號量互斥鎖的問題。使用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 .......
等等....
請幫助我。我哪裏錯了?
我建議使用名稱'互斥量'作爲信號量可能會令人困惑 - 在這種情況下,您應該可能使用'互斥量',而不是信號量(不是因爲信號量「但是 - 這只是一個比你需要的更大的錘子)。另外@Gyycon在文件指針位置下面的答案很可能是因爲緩衝數據永遠不會被寫出來 - 至少在一段時間內...... – twalberg
每次寫入或使用unbuffer I/O,即'open()','write()','read()'和'close()'以及兩個文件描述符。 – alk