Can someone explain the mistake in this code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    Can someone explain the mistake in this code

    I was trying to write a program to copy data in one file to another file,but my code was not responding,it was asking for input,can someone explain the problem in my code.
    Code:
    #include<stdio.h>
    #include<pthread.h>
    #include<semaphore.h>
    #include<stdlib.h>
    #define size 5
    char a[size][100];
    FILE *fp1,*fp2;
    int count=0,c1=0,c2=0;
    sem_t empty,full;
    pthread_mutex_t mutex;
    void *fun1()
    {       int n=3;
    	while(n--)
    	{
    		sem_wait(&empty);
    		pthread_mutex_lock(&mutex);
    		if(produce())
    		{
    			printf("error");
    		}
    		/*	else
    			c1++;*/
    		pthread_mutex_unlock(&mutex);
    		sem_post(&full);
    	}
    	pthread_exit(NULL);
    }
    void *fun2()
    {       int n=3;
    	while(n--)
    	{
    		sem_wait(&full);
    		pthread_mutex_lock(&mutex);
    		if(consume())
    		{
    			printf("error");
    		}
    		/*	else
    			c2++;*/
    		pthread_mutex_unlock(&mutex);
    		sem_post(&empty);
    	}
    	pthread_exit(NULL);
    }
    int produce()
    {       
    	if(count<size)
    	{
    		fgets(a[count],100,fp1);
    		count++;
    	}
    	return 0;
    }
    int consume()
    {      
    	if(count>0)
    	{
    		fputs(a[count],fp2);
    		count--;
    	}
    	return 0;
    }
    int main(int argc,char *argv[])
    {
    	int rc,i;
    	pthread_t pthread[5];
    	pthread_t cthread[2];
    	fp1= fopen(argv[1],"r");
    	fp2= fopen(argv[2],"w");
    	pthread_attr_t attr;
    	pthread_attr_init(&attr);
    	pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    	sem_init(&full,0,0);
    	sem_init(&empty,0,size);
    	pthread_mutex_init(&mutex,NULL);
    	for(i=0;i<5;i++)
    	{
    		rc=pthread_create(&pthread[i],&attr,fun1,NULL);
    		if(rc)
    		{
    			printf("pthread %d creation error",i);
    		}
    	}
    	for(i=0;i<2;i++)
    	{
    		rc=pthread_create(&cthread[i],&attr,fun2,NULL);
    		if(rc)
    		{
    			printf("cthread creation error");
    		}
    	}
    	for(i=0;i<5;i++)
    	pthread_join(pthread[i],NULL);
    	for(i=0;i<2;i++)
    	pthread_join(cthread[i],NULL);
    	pthread_exit(NULL);
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I did not debug your code but I sis notice that in several places you identify a fatal error condition but you do not stop the program. The program after that point is unstable.

    I would start by putting an exit(1) after those fatal errors and see if that helps.

    Comment

    Working...