在多线程环境中,fprintf 函数本身并不是线程安全的
为了在多线程环境中使用 fprintf 函数,你可以采取以下措施:
#include<stdio.h>#include <stdlib.h>#include <pthread.h>pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER;void *thread_function(void *arg) { // 获取互斥锁 pthread_mutex_lock(&file_mutex); // 使用 fprintf 函数写入文件 FILE *file = fopen("output.txt", "a"); if (file != NULL) { fprintf(file, "Thread %ld wrote to the file.\n", (long)arg); fclose(file); } // 释放互斥锁 pthread_mutex_unlock(&file_mutex); return NULL;}使用线程局部存储(Thread Local Storage,TLS)将每个线程的输出缓冲到一个独立的缓冲区,然后在适当的时候将这些缓冲区的内容合并到共享文件中。这种方法可以减少对共享资源的争用,提高程序的性能。
使用线程安全的文件 I/O 库,如 GNU 的 g_async_safe_printf 函数。这些库通常会使用低级别的系统调用(如 write)来实现线程安全的文件操作,而不是使用标准 C 库中的 fprintf 函数。
请注意,这些方法可能会影响程序的性能和可移植性。在选择解决方案时,请根据你的具体需求进行权衡。


