GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Feb-2008, 11:58
kenkoh kenkoh is offline
New Member
 
Join Date: Feb 2008
Posts: 7
kenkoh is on a distinguished road

Problem using pthread


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.

CPP / C++ / C 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);
}
  #2  
Old 25-Feb-2008, 14:59
seprich seprich is offline
Member
 
Join Date: Jun 2007
Posts: 110
seprich has a spectacular aura aboutseprich has a spectacular aura about

Re: Problem using pthread


CPP / C++ / C Code:
// ==================== 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");

/*  should check if  fopen succeeded. e.g. if folder /temp/ does not exist 
 *  or no writing permissions etc. possibilities always exist and should be
 *  anticipated
*/

	pthread_mutex_lock(&mymutex);

      /*  for one thing there is no initial value for global_data.
       *  secondly this seems to be ending condition also.
       *  your first thread never sets the value of global_data to zero
       * before calling _broadcast. therefore this loop can never end.
       *  and file is thus never flushed, never closed...
       */
	while (global_data != 0) {
	pthread_cond_wait(&cond_sample_limit, &mymutex);
	printf("writeval(): Data written to file.\n");

        /**
          *  But the following is really breaker because global_data
          *  is currently just one integer. Therefore the obj_cnt should
          *  be 1 instead of 1000.. and still it would write the integer
          *  to the file in a binary format... perhaps wasn't the idea ??
          */
	fwrite(&global_data, obj_size,obj_cnt, p_file);
	}

  	pthread_mutex_unlock(&mymutex);

        /*  If you exit THIS thread before the file is closed then it is 
             never really closed !
        */
  	pthread_exit(NULL);

        /*  cannot flush the writing buffer after file has already been closed!
         *  but then fclose() does automatically flush the outbuffer into the file
         *  before closing so using fflush is not called for. 
         */
	fclose(p_file);
	fflush(stdout);
}
  #3  
Old 26-Feb-2008, 02:56
seprich seprich is offline
Member
 
Join Date: Jun 2007
Posts: 110
seprich has a spectacular aura aboutseprich has a spectacular aura about

Re: Problem using pthread


also :
  • main function should not call "pthread_exit(NULL);" because main execution thread is not pthread.
  • main function should return int which is missing.
  • According to documentation:
    • Quote:
      In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialise mutexes that are statically allocated. The effect is equivalent to dynamic initialisation by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed.
    • Quote:
      Attempting to initialise an already initialised mutex results in undefined behaviour.
    in other words if you use macro do not use pthread_mutex_init() and vice versa. The same goes for pthread_cond_init()
 
 

Recent GIDBlogToyota - 2009 May Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Graphic problem in Unreal Tournament 2004 zerox Computer Software Forum - Games 10 09-Oct-2005 13:31
Runtime Problem involving "printf" in C Program supamakia C Programming Language 2 09-Oct-2005 11:09
a significant problem after installing Xp mohammad Computer Software Forum - Windows 10 09-Aug-2005 08:03
String problem vaha C Programming Language 3 24-May-2005 19:21
Another FX 5600 problem (but with details that might shed light on this) BobDaDuck Computer Hardware Forum 2 16-Apr-2004 08:53

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 13:21.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.