使用POSIX线程的文件操作

时间:2014-07-24 12:41:21

标签: c file-io pthreads

我正在学习多线程的概念,我遇到了使用信号量互斥量的问题。

这是我的代码段:

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 .......

依旧......

请帮帮我。我哪里错了?

1 个答案:

答案 0 :(得分:1)

线程1写入文件,并将文件指针前进到文件末尾。线程2从文件指针读取,该指针指向文件的末尾,因此您什么也得不到。

您可以使用fseek,或在主题2中回放来获取数据。