Sponsored Content
Top Forums Programming bounded buffer implementation Post 302572894 by amejoish on Friday 11th of November 2011 03:14:15 PM
Old 11-11-2011
Code:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<dirent.h>
#include<semaphore.h>
#include<pthread.h>

char *buffer1[10];
char *buffer2[10];

int in =0;
int out =0 ;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

sem_t empty,full;
void *stage1();
void *stage2();

int main(){
	pthread_t thrd1,thrd2;
	
	sem_init(&empty, 0, 10);
	sem_init(&full,0,0);
	int tid1 = pthread_create(&thrd1,NULL,&stage1,(void *)0);
	if(tid1 == -1)
	perror("cant create thread \n");
	int tid2 = pthread_create(&thrd2,NULL,&stage2,(void *)0);
    if(tid2 == -1)
    perror("cant create thread \n");
    
     pthread_join(thrd1, NULL);
     pthread_join(thrd2, NULL);
//getchar();
pthread_exit(NULL);

}

void *stage1(){
	//printf("Inside thread 1 \n");
DIR *directory;
struct dirent *dir;
int in = 0;

directory = opendir(".");



while((dir=readdir(directory))!=NULL){
	if (strcmp(dir->d_name, ".") == 0|| strcmp(dir->d_name, "..")==0)
               continue;  
   sem_wait(&empty);
   printf("buffer is not empty \n");
   pthread_mutex_lock(&mutex);
   //printf("thread 1 got access \n");
    /* if got access enter filename into buffer */ 
   buffer1[in]=dir->d_name;
   printf(" %s in buffer 1 now \n",buffer1[in]);
   in=(in+1)%10;
   pthread_mutex_unlock(&mutex);
   sem_post(&full);//indicate consumer filename is available
      }
   
   closedir(directory);

pthread_exit(NULL);
}


void *stage2(){
	//printf("Inside thread2 also \n");
int in2 = 0;

struct stat sb;
int fsize = 4096;
	
	while(1){
	//printf("File = %s ,File size = %d \n",buffer[i],(int)sb.st_size);
			sem_wait(&full);
			printf("buffer is full goin ahead\n");
			pthread_mutex_lock(&mutex);
			//printf("thread2 got access \n");
	        if(stat(buffer1[out],&sb)==-1){
				pthread_mutex_unlock(&mutex);
			    break;
		   }	
    else if((int)sb.st_size > fsize){
				
    buffer2[in2] = buffer1[out];
    buffer1[out] = NULL;
    printf(" file = %s and size = %d \n",buffer2[in2],(int)sb.st_size);
    in = (in+1)%10;
    out = (out+1)%10;
    
   pthread_mutex_unlock(&mutex);
   printf("thread 2 unlocked mutex \n");
   sem_post(&empty);
     
}else{
	out = (out+1)%10;
	pthread_mutex_unlock(&mutex);

}
}


pthread_exit(NULL);
}

i changed the condition but i think i am missing something.

Regards,
Ameya
 

10 More Discussions You Might Find Interesting

1. Programming

Frame buffer implementation in Linux

At present, Iam working on Linux Framebuffer device console. I have a doubt sir. Please solve this. *How to display a string or a character in Frame buffer in C language? *What is the library file (is it <linux/fb.h> or other one?) used to do all I/O function manipulations like printing,... (0 Replies)
Discussion started by: chandra80
0 Replies

2. Shell Programming and Scripting

Need help on AWK implementation

Hi, I am accepting a string from user. compare this output with the awk output as below... echo "\n\n\tDay : \c" read day awk '{ if($day == $2) { if ($mon == $1) { print "Yes" }}}' syslog.txt I am getting the follwoing error awk: Field $() is not correct. The input line... (5 Replies)
Discussion started by: EmbedUX
5 Replies

3. Programming

Malloc implementation in C

Hey Guys I am trying to implement the malloc function for my OS class and I am having a little trouble with it. I would be really grateful if I could get some hints on this problem. So I am using a doubly-linked list as my data structure and I have to allocate memory for it (duh...). The... (1 Reply)
Discussion started by: Gambit_b
1 Replies

4. UNIX for Advanced & Expert Users

Malloc Implementation in C

Hey Guys Some of my friends have got together and we are trying to write a basic kernel similar to Linux. I am trying to implement the malloc function in C and I am using a doubly linked list as the primary data structure. I need to allocate memory for this link list (duh...) and I don't feel... (2 Replies)
Discussion started by: rbansal2
2 Replies

5. Linux

CAPWAP implementation

Hi I'm trying to implement CAPWAP protocol for my application.i'm able to configure my server side but i'm getting error at client(WTP) side as IOCTL error.while running the command #./WTP /mnt/cf/capwap/ : wlan2 Starting WTP... # WTP Loads... (0 Replies)
Discussion started by: ran789
0 Replies

6. UNIX for Dummies Questions & Answers

Lseek implementation

Hi everybody, i've been googling for ages now and gotten kinda desperate... The question, however, might be rather trivial for the experts: What is it exactly, i.e. physically, the POSIX function (for a file) "lseek" does? Does it trigger some kind of synchronization on disk? Is it just for the... (4 Replies)
Discussion started by: Humudituu
4 Replies

7. UNIX for Advanced & Expert Users

Ipsec implementation

How can i implement Ipsec between two machines in linux_ ubuntu? any link?? suggestion?? (0 Replies)
Discussion started by: elinaz
0 Replies

8. Homework & Coursework Questions

Bounded Buffer is hanging, tried all I can. (C++)

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: My problem is that when creating my producers and consumers, if I don't create an equal number of both, the... (12 Replies)
Discussion started by: digitalbrainiac
12 Replies

9. Programming

C: CSV implementation

I have this code from a programming book: #include <stdio.h> #include <string.h> char buf; /* input line buffer */ char* field; /* fields */ char* unquote( char* ); /* csvgetline: read and parse line, return field count */ /* sample input:... (3 Replies)
Discussion started by: totoro125
3 Replies

10. Shell Programming and Scripting

XML text bounded with tag

Could you please give your inputs on the below issue: source.xml <?xml version="1.0" encoding="UTF-16"?> <P1 > <C1 type="i"><2></C1> <V1 type="string"><6.2></V1> <D1 type="string"> <D2><1.0></D2> <D2><2.0></D2> </D1> ...................... ...................... many more... (7 Replies)
Discussion started by: unme
7 Replies
PTHREAD_MUTEXATTR_SETROBUST(3)				     Linux Programmer's Manual				    PTHREAD_MUTEXATTR_SETROBUST(3)

NAME
pthread_mutexattr_getrobust, pthread_mutexattr_setrobust - get and set the robustness attribute of a mutex attributes object SYNOPSIS
#include <pthread.h> int pthread_mutexattr_getrobust(const pthread_mutexattr_t *attr, int *robustness); int pthread_mutexattr_setrobust(const pthread_mutexattr_t *attr, int robustness); Compile and link with -pthread. Feature Test Macro Requirements for glibc (see feature_test_macros(7)): pthread_mutexattr_getrobust(), pthread_mutexattr_setrobust(): _POSIX_C_SOURCE >= 200809L DESCRIPTION
The pthread_mutexattr_getrobust() function places the value of the robustness attribute of the mutex attributes object referred to by attr in *robustness. The pthread_mutexattr_setrobust() function sets the value of the robustness attribute of the mutex attributes object referred to by attr to the value specified in *robustness. The robustness attribute specifies the behavior of the mutex when the owning thread dies without unlocking the mutex. The following values are valid for robustness: PTHREAD_MUTEX_STALLED This is the default value for a mutex attributes object. If a mutex is initialized with the PTHREAD_MUTEX_STALLED attribute and its owner dies without unlocking it, the mutex remains locked afterwards and any future attempts to call pthread_mutex_lock(3) on the mutex will block indefinitely. PTHREAD_MUTEX_ROBUST If a mutex is initialized with the PTHREAD_MUTEX_ROBUST attribute and its owner dies without unlocking it, any future attempts to call pthread_mutex_lock(3) on this mutex will succeed and return EOWNERDEAD to indicate that the original owner no longer exists and the mutex is in an inconsistent state. Usually after EOWNERDEAD is returned, the next owner should call pthread_mutex_consistent(3) on the acquired mutex to make it consistent again before using it any further. If the next owner unlocks the mutex using pthread_mutex_unlock(3) before making it consistent, the mutex will be permanently unus- able and any subsequent attempts to lock it using pthread_mutex_lock(3) will fail with the error ENOTRECOVERABLE. The only permit- ted operation on such a mutex is pthread_mutex_destroy(3). If the next owner terminates before calling pthread_mutex_consistent(3), further pthread_mutex_lock(3) operations on this mutex will still return EOWNERDEAD. Note that the attr argument of pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() should refer to a mutex attributes object that was initialized by pthread_mutexattr_init(3), otherwise the behavior is undefined. RETURN VALUE
On success, these functions return 0. On error, they return a positive error number. In the glibc implementation, pthread_mutexattr_getrobust() always return zero. ERRORS
EINVAL A value other than PTHREAD_MUTEX_STALLED or PTHREAD_MUTEX_ROBUST was passed to pthread_mutexattr_setrobust(). VERSIONS
pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() were added to glibc in version 2.12. CONFORMING TO
POSIX.1-2008. NOTES
In the Linux implementation, when using process-shared robust mutexes, a waiting thread also receives the EOWNERDEAD notification if the owner of a robust mutex performs an execve(2) without first unlocking the mutex. POSIX.1 does not specify this detail, but the same behav- ior also occurs in at least some other implementations. Before the addition of pthread_mutexattr_getrobust() and pthread_mutexattr_setrobust() to POSIX, glibc defined the following equivalent nonstandard functions if _GNU_SOURCE was defined: int pthread_mutexattr_getrobust_np(const pthread_mutexattr_t *attr, int *robustness); int pthread_mutexattr_setrobust_np(const pthread_mutexattr_t *attr, int robustness); Correspondingly, the constants PTHREAD_MUTEX_STALLED_NP and PTHREAD_MUTEX_ROBUST_NP were also defined. These GNU-specific APIs, which first appeared in glibc 2.4, are nowadays obsolete and should not be used in new programs. EXAMPLE
The program below demonstrates the use of the robustness attribute of a mutex attributes object. In this program, a thread holding the mutex dies prematurely without unlocking the mutex. The main thread subsequently acquires the mutex successfully and gets the error EOWN- ERDEAD, after which it makes the mutex consistent. The following shell session shows what we see when running this program: $ ./a.out [original owner] Setting lock... [original owner] Locked. Now exiting without unlocking. [main thread] Attempting to lock the robust mutex. [main thread] pthread_mutex_lock() returned EOWNERDEAD [main thread] Now make the mutex consistent [main thread] Mutex is now consistent; unlocking Program source #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #define handle_error_en(en, msg) do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) static pthread_mutex_t mtx; static void * original_owner_thread(void *ptr) { printf("[original owner] Setting lock... "); pthread_mutex_lock(&mtx); printf("[original owner] Locked. Now exiting without unlocking. "); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t thr; pthread_mutexattr_t attr; int s; pthread_mutexattr_init(&attr); /* initialize the attributes object */ pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); /* set robustness */ pthread_mutex_init(&mtx, &attr); /* initialize the mutex */ pthread_create(&thr, NULL, original_owner_thread, NULL); sleep(2); /* "original_owner_thread" should have exited by now */ printf("[main thread] Attempting to lock the robust mutex. "); s = pthread_mutex_lock(&mtx); if (s == EOWNERDEAD) { printf("[main thread] pthread_mutex_lock() returned EOWNERDEAD "); printf("[main thread] Now make the mutex consistent "); s = pthread_mutex_consistent(&mtx); if (s != 0) handle_error_en(s, "pthread_mutex_consistent"); printf("[main thread] Mutex is now consistent; unlocking "); s = pthread_mutex_unlock(&mtx); if (s != 0) handle_error_en(s, "pthread_mutex_unlock"); exit(EXIT_SUCCESS); } else if (s == 0) { printf("[main thread] pthread_mutex_lock() unexpectedly succeeded "); exit(EXIT_FAILURE); } else { printf("[main thread] pthread_mutex_lock() unexpectedly failed "); handle_error_en(s, "pthread_mutex_lock"); } } SEE ALSO
get_robust_list(2), set_robust_list(2), pthread_mutex_init(3), pthread_mutex_consistent(3), pthread_mutex_lock(3), pthreads(7) Linux 2019-03-06 PTHREAD_MUTEXATTR_SETROBUST(3)
All times are GMT -4. The time now is 03:23 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy