From 0f2658daba51b007d142208169949614215d2260 Mon Sep 17 00:00:00 2001 From: Nick Croucher Date: Tue, 23 Apr 2024 11:21:41 +0100 Subject: [PATCH] Enable thread safe printing --- src/block_tab_file.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/block_tab_file.c b/src/block_tab_file.c index 4eadfb51..409d9f9c 100644 --- a/src/block_tab_file.c +++ b/src/block_tab_file.c @@ -21,10 +21,18 @@ #include #include #include "block_tab_file.h" +#include + +// Define a mutex variable +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void print_block_details(FILE * block_file_pointer, int start_coordinate, int end_coordinate, int number_of_snps, char * current_node_id, char * parent_node_id, char * taxon_names, int number_of_child_nodes, double neg_log_likelihood) { - fprintf(block_file_pointer, "FT misc_feature %d..%d\n", start_coordinate, end_coordinate); + + // Lock the mutex before accessing the file + pthread_mutex_lock(&mutex); + + fprintf(block_file_pointer, "FT misc_feature %d..%d\n", start_coordinate, end_coordinate); fprintf(block_file_pointer, "FT /node=\"%s->%s\"\n",parent_node_id,current_node_id); fprintf(block_file_pointer, "FT /neg_log_likelihood=\"%f\"\n",neg_log_likelihood); @@ -39,11 +47,19 @@ void print_block_details(FILE * block_file_pointer, int start_coordinate, int en fprintf(block_file_pointer, "FT /taxa=\"%s\"\n",taxon_names); fprintf(block_file_pointer, "FT /SNP_count=\"%d\"\n",number_of_snps); fflush(block_file_pointer); + + // Unlock the mutex after accessing the file + pthread_mutex_unlock(&mutex); + } void print_branch_snp_details(FILE * branch_snps_file_pointer, char * current_node_id, char * parent_node_id, int * branches_snp_sites, int number_of_branch_snps, char * branch_snp_sequence, char * branch_snp_ancestor_sequence,char * taxon_names) { + + // Lock the mutex before accessing the file + pthread_mutex_lock(&mutex); + int i = 0; for(i=0; i< number_of_branch_snps; i++) { @@ -55,4 +71,8 @@ void print_branch_snp_details(FILE * branch_snps_file_pointer, char * current_no fprintf(branch_snps_file_pointer, "FT /replace=\"%c\"\n",branch_snp_sequence[i]); fflush(branch_snps_file_pointer); } + + // Unlock the mutex after accessing the file + pthread_mutex_unlock(&mutex); + }