Thread: pthreads/arrays Problem

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    5

    pthreads/arrays Problem

    Hey guys, I have a bit of a head scratcher as far as this program goes right now.

    The program is a simulation of a movie rental using pthreads. It starts by reading in a file, which sets all of the variables (worker threads, client threads, how many movies and of what, etc). I have the movies that are found in the init file put into a char * array, and printing them right after I store them yields the correct movie title found at the correct index, code snippet below from my init() function

    Code:
    int nMovies = 0;
    ...
    while ( fgets ( line, sizeof line, file ) != NULL ) 
    		{
                        ...(if movie found)
    				movies[nMovies] = line;
    				cMovies[nMovies] = line;
    				printf("Title:%s",cMovies[nMovies]); //Prints out Correct Title
    				nMovies++;
    				...
    		}
    movies[] are the movies found on the server
    cMovies[] are the movies that the client will try to rent (which is the same array with some extra dummie titles to simulate clients trying to rent an invalid movie).

    This part works fine, However, this is where the weird part comes in: after reading the init file, I call to create the client threads:

    Code:
    void startClients(int clients ){
    	clients = nClients;
    	numClients[nClients]; //Global variable of type pthread_t
    	int rc;
       	long t;
    
       	for(t=0; t<nClients; t++){
    
        	  	printf("In main: creating thread %ld\n", t);
        		rc = pthread_create(&numClients[t], NULL, clientThread, (void *)t);
          		
    		if (rc){
            		printf("ERROR; return code from pthread_create() is %d\n", rc);
             	exit(-1);
          		}
    
    		
       	}
    }
    which calls this function after threads are created:

    Code:
    void *clientThread(void *threadid){
    	int tid;
       	tid = (int)threadid;
            //Number of steps (actions of clients) to simulate
    	int steps = nSteps;
    	int i;
    	printf("ThreadID:%d\n",tid);
    	int rv;
    	
    	for(i = 0; i < steps; i++){
    		coin = 0;
    		//wait until the lock is not taken
    		while(true){
    			rv = pthread_mutex_trylock( &clientMutex );
    			if(rv == 0){
    				printf("Working???");
    				break;
    			}
    
    		};
    		printf("Working???");
    		if (coin == 0){
    			randomCheckout(tid);
                            pthread_exit(NULL);
    			break;
    			
    			
    		}else{
    			//randomReturn();
    		}
    		
    		sleep(150);
    	}
    	pthread_mutex_unlock( &clientMutex );
    	printf("\nInside of checkoutVideo \n");
    	pthread_exit(NULL);
    
    }
    This is the first problem: When I run the program, it creates all of the threads perfectly fine, but only the first thread to get the lock will get into the bolded section (even though coin ALWAYS equals 0 right now), and the whole program will only go through 1 step. Am I not releasing the mutex lock correctly or in the wrong place? I tried moving it to after randomCheckout(tid); in the bolded section (instead of break), and ended up with segmentation faults after the first thread went through a step.

    without pthread_exit(NULL); in the bolded section (just break), it gets about half way through the # of client threads and seg faults.

    The next problem comes next, in the randomcheckout() method:

    Code:
    void randomCheckout(int tid){
    	
            //Number of entries in the client's movie array
    	int j = (sizeof cMovies)/4;	
    	printf("\n%d\n", j);
            
            //Randomly pick a number from the array        
    	int selection = rand() % j;
    	printf("%d\n", selection); 
    
    
    	int a;
    	for(a = 0; a < j; a++){
    		printf("\n%s",cMovies[a]);
    
    	}
    
    	printf("%s\n", cMovies[selection]);
    	checkoutVideo(numClients[tid], cMovies[selection]);
    }
    In the bolded section (which is just debugging code cycling through the array), the output is just the number of entries in the array, but all the same movie title (the last one in the init file/stored into the array)...I'm not accessing the array anywhere in between populating it and here, so why are all of the values changing to the last entry??

    Sorry for the bombardment of questions, I've been spending hours upon hours trying to fix these bugs and I just want to pull my hair out

    If you need anything other parts of my code/more description of what's going on, just let me know.

    Thanks for any input!!

    Also for any Mods: I have an old account that I haven't accessed in a while and I guess it was deactivated to posting due to inactivity? Is there anyway to reactivate it?
    Last edited by Jedel; 10-15-2009 at 03:11 AM.

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Code:
    void startClients(int clients ){
    	clients = nClients;
    	numClients[nClients]; //Global variable of type pthread_t
    	int rc;
       	long t;
    
       	for(t=0; t<nClients; t++){
    
        	  	printf("In main: creating thread %ld\n", t);
        		rc = pthread_create(&numClients[t], NULL, clientThread, (void *)t);
          		
    		if (rc){
            		printf("ERROR; return code from pthread_create() is %d\n", rc);
             	exit(-1);
          		}
    
    		
       	}
    }
    Don't have time atm to look on the rest, but the red lines make no sense.
    The first assigns the argument to something. Maybe you wanted
    Code:
    nClinets = clients;
    The second does absolutely nothing!

  3. #3
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
                       ...(if movie found)
    				movies[nMovies] = line;
    				cMovies[nMovies] = line;
    				printf("Title:%s",cMovies[nMovies]); //Prints out Correct Title
    				nMovies++;
    This will set each movies and cMovies to the same value ( line ).
    You have to copy the string
    e.g.
    Code:
                       ...(if movie found)
    				cMmovies[nMovies] = malloc( strlen(line) +1);
                                    strcpy(cMovies[nMovies], line);
    				printf("Title:%s",cMovies[nMovies]); //Prints out Correct Title
    				nMovies++;
    and don't forget to free the strings

    Kurt

  4. #4
    Registered User
    Join Date
    Oct 2009
    Posts
    5
    Thanks for the input guys!

    yeah, my code is a bit messy from trying a whole bunch of things, so there probably are a few statements that don't do much

    Anyway, now I'm stuck getting my pthreads to join...My code for the clients:

    Code:
    void startClients(int clients ){
    	clients = nClients;
    	numClients[nClients];
    	int rc;
       	long t;
    
    	pthread_attr_init(&attr);
      	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
       	for(t=0; t<nClients; t++){
    
        	  	//printf("In main: creating thread %ld\n", t);
        		rc = pthread_create(&numClients[t], &attr, clientThread, (void *)t);
          		
    		if (rc){
            		printf("ERROR; return code from pthread_create() is %d\n", rc);
             	exit(-1);
          		}
    	
       	}
    }
    
    void waitForClients( int clients){
    	int rc;
       	int t;
    	printf("HERE??\n");
    	for(t=0; t< clients; t++) {
    		printf("\nTHIS IS HERE");
          		rc = pthread_join(numClients[t], &attr);
          		if (rc) {
    	 		printf("ERROR; return code from pthread_join() is %d\n", rc);
    	 	exit(-1);
    	 	}
    
    		//pthread_exit(NULL);
          	printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
          	}
    }
    
    //Called when client threads are created
    void *clientThread(void *threadid){
    	int tid;
       	tid = (int)threadid;
    	int steps = nSteps;
    	int i;
    	printf("ThreadID:%d\n",tid);
    	int rv;
    	int count = 0;
    	
    
    	for(i = 0; i < steps; i++){
    		coin = rand() % 1;
    		//wait until the lock is not taken
    		while(true){
    			rv = pthread_mutex_trylock( &c.clientMutex );
    			if(rv == 0){
    				count++;
    				break;
    			}
    		}
    		
    		if (count < SIMULMOVES) {
    			pthread_cond_wait(&c.empty, &c.clientMutex);
    		     // pthread_cond_signal(&c.condVar);
    		      printf("inc_count(): thread , count =   Threshold reached.\n");
    		}
    
    		if (coin == 0){
    			//printf("HERE");
    			randomCheckout(tid);
    			//pthread_exit(NULL);
    			pthread_mutex_unlock( &c.clientMutex );
    			count = 0;
    			//pthread_cond_signal(&c.empty);
    			//break;
    			
    			
    		}else{
    			printf("SHOULD RETURN HERE");
    			randomReturn(tid);
    			count = 0;
    			//pthread_cond_signal(&c.empty);
    		}
    		
    		sleep(2000);
    		
    	}
    	
    	//pthread_mutex_unlock( &c.clientMutex );
    	//printf("\nInside of checkoutVideo \n");
    	pthread_exit(NULL);
    
    }
    my main so far is just:

    Code:
    int main(){
    	init();
    	startClients(nClients);
    	waitForClients(nClients);
    	
    
    	return 0;
    }
    so startClients() is called, which creates the threads, then clientThread() is run, then waitForClients() is called to wait for all of the threads to finish.

    What happens is that all of the threads will go through clientThread() once trying to rent a movie, then after that it goes to waitForClients()..The bolded printf statement is the last thing that outputs before it segfaults on me.

    the thing that I can't figure out is that it is segfaulting even before the call to pthread_join (the statement printf("\nTHIS IS HERE"); never outputs, even if I get rid of the for loop...) which just downright makes no sense to me.

    I have a feeling it has something to do with the way I'm trying to synchronize my threads (the bolded section of code is trying to use a condition variable to see if the lock is taken as I read cond'n variable and mutex's need to be used together, but I'm not quite sure of its implementation).

    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help understanding a problem
    By dnguyen1022 in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2009, 04:21 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM