#include #include #include #include #include //#include #include #include #include // External semaphore functions implemented in sempv.c extern void P (int semid); extern void V (int semid); extern int Init (int* semid, int value); void Remove (int semid); extern void Print (int semid); // Thread structure with ID typedef struct thread_str { pthread_t thread; int id; int num_rounds; int total_size; // Total file size } thread_str; // Semaphores int mutex = 0; // Lock // Global variables int num_files = 10; // Number of files created. Set default to 10. /*****************************************************************************/ // File producer - function is called by every thread. void produce_file (thread_str* producer_thread) { int retval; int i, j; int* list; // Steps: // 1) Get a random number for the number of loop iterations for the thread. // Store in producer_thread->num_rounds. // 2) Add first inode for the thread's file to inode table. This must be // protected in a critical section. // 3) Loop through the number of iterations stored in producer_thread->num_rounds. for (i=0; inum_rounds; i++) { // 4) Apply 35% chance of thread appending to file, 35% chance of thread deleting from file, // 30% chance of thread doing nothing. // 5) Append to file with random number of bytes (increment producer_thread->total_size). // 6) Update inode data structure for file. printf ("Thread %i increasing file size\n", producer_thread->id); sleep (0.01); // To ensure context switching. } // Thread exit. pthread_exit ((void*)(&retval)); } /*****************************************************************************/ // Main function initializes semaphores and creates producer/consumer threads. int main(int argc, char **argv) { thread_str *file_producers; int error, retval[1], s; struct timeval tval_start, tval_prod_end, tval_cons_end; struct timezone tzone; // Get program arguments. num_files = atoi (argv[1]); // Print program arguments printf ("number of files = %i\n", num_files); // Seed random number generator gettimeofday (&tval_start, &tzone); srandom (tval_start.tv_usec); // Initializing semaphores. Init (&mutex, 1); Print (mutex); // Creating threads - these should be dynamically allocated // since the number of producers/consumers is a program argument. printf ("Creating threads!\n"); file_producers = (thread_str*) calloc (num_files, sizeof(thread_str)); for (s=0; s