gpt4 book ai didi

c - 使用 POSIX 线程进行文件操作

转载 作者:行者123 更新时间:2023-11-30 15:31:15 24 4
gpt4 key购买 nike

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

这是我的代码片段:

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 写入文件,并将文件指针前进到文件末尾。线程 2 从文件指针读取数据,该指针指向文件末尾,因此您什么也得不到。

您可以使用 fseek 或在线程 2 中倒带来获取数据。

关于c - 使用 POSIX 线程进行文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com