Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Threads_posix
//Threads in C /* Includes */ #include <unistd.h> /* Symbolic Constants */ //#include <sys/types.h> /* Primitive System Data Types */ //#include <errno.h> /* Errors */ #include <stdio.h> /* Input/Output */ #include <stdlib.h> /* General Utilities */ #include <pthread.h> /* POSIX Threads */ #include <string.h> /* String handling */ /* prototype for thread routine */ void *read_func(void *ptr); void *write_func(void *ptr); #define NUM_READERS 5 #define NUM_WRITERS 5 int g_shared, g_readers, g_waiting_readers; pthread_mutex_t g_lock; pthread_cond_t p_read = PTHREAD_COND_INITIALIZER; pthread_cond_t p_write = PTHREAD_COND_INITIALIZER; int main() { pthread_t r_thread[NUM_READERS], w_thread[NUM_WRITERS]; /* thread variables */ int r_id[NUM_READERS], w_id[NUM_WRITERS]; int i; if (pthread_mutex_init(&g_lock, NULL) != 0) { printf("\n mutex init has failed\n"); return 1; } for (i = 0; i < NUM_READERS; i++) { r_id[i] = i; pthread_create (&r_thread[i], NULL, (void *) &read_func, &r_id[i]); } for (i = 0; i < NUM_WRITERS; i++) { w_id[i] = i; pthread_create (&w_thread[i], NULL, (void *) &write_func, &w_id[i]); } for (i = 0; i < NUM_READERS; i++) pthread_join(r_thread[i], NULL); for (i = 0; i < NUM_READERS; i++) pthread_join(w_thread[i], NULL); return 0; } /* main() */ void *read_func(void *data) { int *r_id = (int *)data; int i; for (i = 0; i < NUM_READERS; i++) { usleep(1000 * (random() % NUM_READERS + NUM_WRITERS)); /*wait random*/ pthread_mutex_lock(&g_lock); g_waiting_readers++; while (g_readers == -1) pthread_cond_wait(&p_read, &g_lock); g_waiting_readers--; g_readers++; pthread_mutex_unlock(&g_lock); printf("Reader_id:%d Shared_value %d num_readers:%d\n", *r_id, g_shared, g_readers); pthread_mutex_lock(&g_lock); g_readers--; if (g_readers == 0) pthread_cond_signal(&p_write); pthread_mutex_unlock(&g_lock); } return NULL; } void *write_func(void *data) { int *w_id = (int *)data; int i; for (i = 0; i < NUM_WRITERS; i++) { usleep(100 * (random() % NUM_READERS + NUM_WRITERS)); /*wait random*/ pthread_mutex_lock(&g_lock); while (g_readers != 0) pthread_cond_wait(&p_write, &g_lock); g_readers = -1; pthread_mutex_unlock(&g_lock); printf("Writer_id:%d Shared_value %d num_readers:%d\n", *w_id, ++g_shared, g_readers + 1); pthread_mutex_lock(&g_lock); g_readers = 0; if (g_waiting_readers > 0) { pthread_cond_signal(&p_read); } else { pthread_cond_signal(&p_write); } pthread_mutex_unlock(&g_lock); } return NULL; }
run
|
edit
|
history
|
help
0
SumIt
funciones serie de taylor
1233333
Stub Program for Problem 4 HW 2
Character testing
150116_MatrizOrdenada
Fgets and String Stuff
Max
Coba
X=1