Hi there,
I’m trying out on a simple example to read and write values at the same time using the mutex and condition (so that the write process will only execute after specific number of samples). I simply generated a vector of integers (in global_data) and will like to save it as binaries in an output (.log) file.
However, I’ve got a problem trying to get it working. It seems like the writeval function didn’t get “triggered” after the condition is met. Please kindly advise me if I'm missing something here.
Thanks for any help in advance.
Code:
/******************************************************************************
* DESCRIPTION:
* Example code for using Pthreads condition variables. The global data gets
* incremented (in readval function) and everything it reaches nLimit, the
* writeval function will write and append the array to a output file.
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 2
int global_data;
int nSamples = 10000;
int nLimit = 1000;
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_sample_limit = PTHREAD_COND_INITIALIZER;
void *readval(void *arg);
void *writeval(void *arg);
// ============================== Main Program ==============================
int main()
{
int i;
pthread_t threads[NUM_THREADS];
// Initialise mutex and condition
pthread_mutex_init(&mymutex, NULL);
pthread_cond_init (&cond_sample_limit, NULL);
if (pthread_create(&threads[0], NULL, readval, NULL)) {
printf("error creating reading_thread.\n"); abort();
}
if (pthread_create(&threads[1], NULL, writeval, NULL)) {
printf("error creating writing_thread.\n"); abort();
}
/* Join all threads upon completion*/
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf ("Main(): Completion on %d threads. Done.\n", NUM_THREADS);
pthread_mutex_destroy(&mymutex);
pthread_cond_destroy(&cond_sample_limit);
pthread_exit (NULL);
}
// ==================== Reading Values from Device =====================
void *readval(void *arg)
{
int i,j, count;
for ( i=0; i<nSamples; i++ ) {
j=global_data;
j++;
global_data=j;
pthread_mutex_lock(&mymutex);
if (i!=0 && i%nLimit==0) {
pthread_cond_broadcast(&cond_sample_limit);
printf("readval(): count = %d Threshold reached.\n", i);
}
pthread_mutex_unlock(&mymutex);
}
pthread_exit(NULL);
}
// ====================== Writing Values to File =======================
void *writeval(void *arg)
{
size_t obj_size=sizeof(int);
size_t obj_cnt=sizeof(nLimit)/sizeof(int);
FILE *p_file;
char *filename= "/temp/output.log";
p_file=fopen(filename,"w");
pthread_mutex_lock(&mymutex);
while (global_data != 0) {
pthread_cond_wait(&cond_sample_limit, &mymutex);
printf("writeval(): Data written to file.\n");
fwrite(&global_data, obj_size,obj_cnt, p_file);
}
pthread_mutex_unlock(&mymutex);
pthread_exit(NULL);
fclose(p_file);
fflush(stdout);
}