Thread: Need help with pthread (multi-threading)

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    12

    Need help with pthread (multi-threading)

    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);
    }

  2. #2
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    It looks good, compiles finely, your mutex_locks appear to be on first sight both correctly placed and semantically correct. And i am still reading the opengroup specs. Maybe i'll make something out.. hold on.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  3. #3
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Quote Originally Posted by kenkoh View Post
    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.
    Code:
    int global_data;
    You simply didn't generate a vector. global_data is a single scalar int, but you are using it as a vector...
    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.
    Code:
    	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);
    	}
    global_data was 0 when the writing thread reached the point therefore no wait was executed and the thread exited silently. Also if global_data was a vector, you would never leave the loop. It would always be !=0 as it would be a pointer to some memory location.
    Code:
      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();
      }
    I would suggest reversing the order of initialization to put all the writing threads to a wait state immediately.
    If you can figure out how to make global_data an actual array, and how to make the writer thread work until it writes all it must, and still have problems post the code and i will be happy to assist with any errors.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Here are the problems I see:
    1) your mutext and condition are intialized twice
    2) there is un-synchronized access to global_data in readval()
    3) you have pthread_exit() in main() - don't know if that's allowed, but it's not needed
    4) pthread_exit() doesn't return - so your file is never closed
    5) flush(stdout) after each printf if you really want to see it

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overlapped I/O and multi threading
    By krishnampkkm in forum C++ Programming
    Replies: 2
    Last Post: 06-22-2009, 03:27 PM
  2. Multi Threading
    By beon in forum C Programming
    Replies: 5
    Last Post: 12-04-2006, 09:21 PM
  3. Replies: 6
    Last Post: 06-02-2006, 08:32 AM
  4. starting to learn multi threading
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 06-09-2004, 01:44 PM
  5. Multi Threading
    By IceBall in forum C Programming
    Replies: 7
    Last Post: 07-13-2003, 03:01 PM