text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> union recv_msgs { struct reg_msg client_msg; struct _pulse pulse; uint16_t type; } recv_buf; int save_rcvid = 0; int save_scoid = 0; struct sigevent save_event; int notify_count = 0; pthread_mutex_t save_data_mutex; void * notify_thread( void * ignore); int main(int argc, char *argv[]) { name_attach_t *att; int rcvid; struct _msg_info msg_info; att = name_attach(0,RECV_NAME, 0 ); if (0 == att ) { perror("event_server: " "name_attach()"); exit(1); } pthread_mutex_init( &save_data_mutex, 0 ); pthread_create( 0, 0, notify_thread, 0 ); while(1) { rcvid = MsgReceive( att->chid, &recv_buf, sizeof (recv_buf), &msg_info ); if( -1 == rcvid ) { perror("event_server: " "MsgReceive failed"); continue; } if ( 0 == rcvid ) { switch( recv_buf.pulse.code ) { case _PULSE_CODE_DISCONNECT: pthread_mutex_lock( &save_data_mutex ); if( save_scoid == recv_buf.pulse.scoid ) { save_scoid = 0; save_rcvid = 0; } pthread_mutex_unlock( &save_data_mutex ); ConnectDetach( recv_buf.pulse.scoid ); printf("event_server: " "disconnect from a client %X\\n", recv_buf.pulse.scoid); break; case _PULSE_CODE_UNBLOCK: printf("event_server: " "got an unblock pulse, did you forget to reply to your client?\\n"); MsgError( recv_buf.pulse.value.sival_int, EINTR ); break; default: printf("event_server: " "unexpect pulse code: %d\\n", recv_buf.pulse.code ); break; } continue; } switch( recv_buf.type ) { case _IO_CONNECT: MsgReply( rcvid, EOK, 0, 0 ); break; case REG_MSG: pthread_mutex_lock( &save_data_mutex ); save_scoid = msg_info.scoid; pthread_mutex_unlock( &save_data_mutex ); printf("event_server: " "got register message from client: %X\\n", rcvid ); break; default: printf("event_server: " "unexpect message type: %d\\n", recv_buf.type ); MsgError(rcvid, ENOSYS ); break; } } } void * notify_thread( void * ignore) { while(1) { sleep(1); pthread_mutex_lock( &save_data_mutex ); if (save_rcvid) { printf("event_server: " "deliver pulse to client %X\\n", save_rcvid); } pthread_mutex_unlock( &save_data_mutex ); } }
1
#include <pthread.h> long *items; long num_items; long next_item; pthread_mutex_t mutex; } tasks_t; long next(tasks_t *tasks) { long ret = -1; pthread_mutex_lock(&tasks->mutex); if(tasks->next_item < tasks->num_items) { ret = tasks->items[tasks->next_item]; tasks->next_item++; } pthread_mutex_unlock(&tasks->mutex); return ret; } long p; long Bp; } result_t; result_t *items; int num_items; pthread_mutex_t mutex; } results_t; long sum = 0; void update(results_t *results, long p, long Bp) { result_t r; r.p = p; r.Bp = Bp; pthread_mutex_lock(&results->mutex); FILE *fp = fopen("results.log", "a"); fprintf(fp, "%ld\\t%ld\\n", p, Bp); fclose(fp); sum += Bp; pthread_mutex_unlock(&results->mutex); } tasks_t *tasks; results_t *results; uint64_t *work; } stuff_t; bool check_and_update(long idx, uint64_t *work) { uint64_t word = idx / 64; uint64_t bit = 1ul << (idx % 64); bool ret = work[word] & bit; work[word] |= bit; return ret; } long B(long p, uint64_t *work) { memset(work, 0, (((1000000000l + 10000000l + 63) / 64) * sizeof(uint64_t))); long a = 1; long i = 0; while(!check_and_update(a, work)) { i++; a = (6*(a)*(a) + 10*(a) + 3) % p; } long cycle_len = i; long cycle_start = a; long z = 1000000000000000l; a = 1; while(a != cycle_start) { cycle_len--; z--; a = (6*(a)*(a) + 10*(a) + 3) % p; } printf("cycle len for p == %ld is %ld (repeats at %ld)\\n", p, cycle_len, cycle_start); z %= cycle_len; a = cycle_start; for(i = 0; i < z - 1; i++) { a = (6*(a)*(a) + 10*(a) + 3) % p; } printf("a_%ld for p == %ld is %ld\\n", 1000000000000000l, p, a); return a; } void *worker(void *vstuff) { stuff_t *stuff = (stuff_t *) vstuff; tasks_t *tasks = stuff->tasks; results_t *results = stuff->results; uint64_t *work = stuff->work; long p; while((p = next(tasks)) != -1) { long Bp = B(p, work); update(results, p, Bp); } return 0; } int main() { long *p, np; primes(100000, &p, &np); long i; FILE *fp = fopen("results.log", "r"); uint64_t *hits = calloc((1000000000l + 10000000l + 63) / 64, sizeof(uint64_t)); if(fp) { printf("logfile found.\\n"); char buf[1024]; while(0 != fgets(buf, sizeof(buf), fp)) { char *tok; tok = strtok(buf, "\\t"); long p = strtol(tok, 0, 10); tok = strtok(0, "\\t"); long Bp = strtol(tok, 0, 10); sum += Bp; check_and_update(p, hits); } fclose(fp); fp = 0; } else printf("no logfile found\\n"); long nt = 0; for(i = 1000000000l; i <= 1000000000l + 10000000l; i++) { if(isprime(i, p, np)) nt++; } tasks_t tasks; tasks.num_items = 0; tasks.items = malloc(nt*sizeof(long)); for(i = 1000000000l; i <= 1000000000l + 10000000l; i++) { if(isprime(i, p, np) && !check_and_update(i, hits)) tasks.items[tasks.num_items++] = i; } free(hits); printf("%ld / %ld tasks remaining, queued.\\n", tasks.num_items, nt); tasks.next_item = 0; pthread_mutex_init(&tasks.mutex, 0); results_t results; pthread_mutex_init(&results.mutex, 0); pthread_t threads[3]; for(i = 0; i < 3; i++) { stuff_t *stuff = malloc(sizeof(stuff_t)); stuff->tasks = &tasks; stuff->results = &results; stuff->work = malloc((((1000000000l + 10000000l + 63) / 64) * sizeof(uint64_t))); pthread_create(threads + i, 0, worker, stuff); } for(i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("sum: %ld\\n", sum); return 0; }
0
#include <pthread.h> int count = 0; void __VERIFIER_atomic_inc() { __atomic_begin(); count++; __atomic_end(); } void __VERIFIER_atomic_dec() { __atomic_begin(); count--; __atomic_end(); } pthread_mutex_t mutexa,mutexb; void my_thread1() { pthread_mutex_lock(&mutexa); __VERIFIER_atomic_inc(); __VERIFIER_atomic_dec(); pthread_mutex_unlock(&mutexa); } void my_thread2() { pthread_mutex_lock(&mutexb); __VERIFIER_atomic_dec(); __VERIFIER_atomic_inc(); pthread_mutex_unlock(&mutexb); } void* thr1(void* arg) { while(1) { pthread_mutex_lock(&mutexa); assert(count >= -1); pthread_mutex_unlock(&mutexa); pthread_mutex_lock(&mutexb); assert(count <= 1); pthread_mutex_unlock(&mutexb); } return 0; } void* thr2(void* arg) { if(__nondet_int()) my_thread1(); else my_thread2(); return 0; } int main(void) { pthread_t t1,t2,t3; pthread_create(&t1, 0, thr1, 0); pthread_create(&t2, 0, thr2, 0); pthread_create(&t3, 0, thr2, 0); return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int sum = 0; void *inc(void *arg) { int i = (*(int *)arg); pthread_mutex_lock(&mutex); sum = sum + i; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]) { pthread_t pt[10]; int args[10]; for (int i = 0; i < 10; i++) { args[i] = i; if (pthread_create(&pt[i], 0, inc, (void *)&args[i]) != 0) { printf("pthread_create error\\n"); exit(1); } } for (int i = 0; i < 10; i++) { if (pthread_join(pt[i], 0) != 0) { printf("pthread_join error\\n"); exit(1); } } printf("sum is %d\\n", sum); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> struct thread_args { int tid; int inc; int loop; }; int count = 0; pthread_mutex_t count_mutex; void *inc_count(void *arg) { int i,loc; struct thread_args *my_args = (struct thread_args*) arg; loc = 0; for (i = 0; i < my_args->loop; i++) { pthread_mutex_lock(&count_mutex); count = count + my_args->inc; pthread_mutex_unlock(&count_mutex); loc = loc + my_args->inc; } printf("Thread: %d finished. Counted: %d\\n", my_args->tid, loc); free(my_args); pthread_exit(0); } int main(int argc, char *argv[]) { int i, loop, inc; struct thread_args *targs; pthread_t threads[3]; pthread_attr_t attr; if (argc != 3) { printf("Usage: PTCOUNT LOOP_BOUND INCREMENT\\n"); exit(0); } loop = atoi(argv[1]); inc = atoi(argv[2]); pthread_mutex_init(&count_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 3; i++) { targs = malloc(sizeof(targs)); targs->tid = i; targs->loop = loop; targs->inc = inc; pthread_create( &threads[i] , &attr , inc_count , targs ); } for (i = 0; i < 3; i++) { pthread_join(threads[i] , 0); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_exit (0); }
1
#include <pthread.h> int thID; int min; int max; } arg; int **a; int c = 0; int N, M, T; pthread_mutex_t mx; void tres (arg *args) { int i, j; for (i=args->min; i<args->max; i++) { for (j=0; j<M; j++) { if (a[i][j] == 3) { pthread_mutex_lock(&mx); c++; pthread_mutex_unlock(&mx); } } } } main (int argc, char *argv[]) { struct timeval ts, tf; int i, j; int cl, fr; pthread_t *th; arg *args; if (argc != 4) {printf ("USO: %s <dimX> <dimY> <Ths>\\n", argv[0]); exit (1);} N = atoi(argv[1]); M = atoi(argv[2]); T = atoi(argv[3]); th = malloc (T * sizeof (pthread_t)); a = malloc (N * sizeof (int *)); args = malloc (T * sizeof (arg)); if (a==0 || th==0 || args==0) { printf ("Memoria\\n"); exit (1);} for (i=0; i<N; i++) { a[i] = malloc (M * sizeof (int)); if (a[i] == 0) { printf ("Memoria\\n"); exit (1);} } srandom (177845); for (i=0; i<N; i++) for (j=0; j<M; j++) a[i][j] = random() % 10; (void) pthread_mutex_init(&mx, 0); cl = (int)ceil((float)N/(float)T); fr = (int)floor((float)N/(float)T); for (i=0; i<N%T; i++) { args[i].thID = i; args[i].min = i*cl; args[i].max = (i+1)*cl; } for (i=N%T; i<T; i++) { args[i].thID = i; args[i].min = (N%T)*cl + (i-(N%T))*fr; args[i].max = (N%T)*cl + (i-(N%T)+1)*fr; } gettimeofday (&ts, 0); for (i=0; i<T; i++) pthread_create (&th[i], 0, (void *) tres, (void *)&args[i]); for (i=0; i<T; i++) if (pthread_join (th[i], 0)) {printf ("PJOIN (%d)\\n", i); exit (1);}; gettimeofday (&tf, 0); printf ("TRES: %d (%f secs)\\n", c, ((tf.tv_sec - ts.tv_sec)*1000000u + tf.tv_usec - ts.tv_usec)/ 1.e6); exit (0); }
0
#include <pthread.h> int check_path(char *path); int check_path(char *path) { int ptr; size_t pathlen; int depth; pathlen = strlen(path); depth = -1; for (ptr = 0; ptr < pathlen; ++ptr) { if (path[ptr] == '\\\\') path[ptr] = '/'; if (path[ptr] == '/') { ++depth; } else if (path[ptr] == '.') { if ((ptr+1 < pathlen) && (path[ptr+1] == '.')) { --depth; if (depth < 0) { return 0; } } } } return 1; } int server_fs_create(struct server_filesystem *fs, char *rootDirectory, char *logFile, int useflock) { struct stat st_buf; int status; status = stat(rootDirectory, &st_buf); if (status == -1 || !S_ISDIR(st_buf.st_mode)) { return FS_BADROOT; } status = stat(logFile, &st_buf); if (status == 0 && S_ISDIR(st_buf.st_mode)) { return FS_BADLOG; } if ((fs->log_fd = open(logFile, O_CREAT | O_APPEND | O_WRONLY, 0777)) == -1) { return FS_BADLOG; } fs->useflock = useflock; if (useflock == 0) { if (0 != pthread_mutex_init(&fs->log_pthread_lock, 0)) { return FS_INITERROR; } } fs->root_dir = rootDirectory; fs->log_dir = logFile; return FS_OKAY; } int server_fs_open(struct server_filesystem *fs, char *path) { size_t totallen; char *fullpath; struct stat st_buf; int status; int fd; if (!check_path(path)) { return FS_EFILE_FORBIDDEN; } totallen = strlen(fs->root_dir) + strlen(path); fullpath = malloc(totallen + 1); strcpy(fullpath, fs->root_dir); strcpy(fullpath + strlen(fs->root_dir), path); fullpath[totallen] = '\\0'; status = stat(fullpath, &st_buf); if (status == -1) { return FS_EFILE_NOTFOUND; } if (!S_ISREG(st_buf.st_mode)) { return FS_EFILE_FORBIDDEN; } fd = open(fullpath, O_RDONLY); free(fullpath); if (fd == -1) return FS_EFILE_NOTFOUND; else return fd; } void server_fs_destroy(struct server_filesystem *fs) { close(fs->log_fd); if (!fs->useflock) { pthread_mutex_destroy(&fs->log_pthread_lock); } } void server_fs_log(struct server_filesystem *fs, char* format, ...) { if (fs->useflock) flock(fs->log_fd, LOCK_EX); else pthread_mutex_lock(&fs->log_pthread_lock); va_list arglist; __builtin_va_start((arglist)); vdprintf(fs->log_fd, format, arglist); ; if (fs->useflock) flock(fs->log_fd, LOCK_UN); else pthread_mutex_unlock(&fs->log_pthread_lock); }
1
#include <pthread.h> void *packer_function(void *ptr){ const char *COLORS[] = {"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGodenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","Darkorange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","God","GodenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGodenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OdLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGodenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"}; struct product *box; box = (struct product *)malloc((size_t)info->n*sizeof(struct product)); int i; int a; a = pthread_self(); while(info->packed < (info->a*info->c)){ for(i = 0; i < info->n; i++){ pthread_mutex_lock(&the_mutex); if(info->packed == info->a*info->c){ pthread_mutex_unlock(&the_mutex); break; } while(info->in == info->out && info->packed < info->a*info->c) pthread_cond_wait(&condc,&the_mutex); if(info->packed == info->a*info->c){ pthread_mutex_unlock(&the_mutex); break; } box[i] = assembly_line[info->out]; info->out = (info->out + 1)%(info->l); info->packed++; pthread_cond_broadcast(&condp); pthread_mutex_unlock(&the_mutex); } if (i != 0){ pthread_mutex_lock(&print_mutex); a = abs(a); while (a>=10000){ a = a/10; } printf("[Packer %d]: ",a); printf("I have a box of products containing: "); for (int j = 0; j < i - 1; j++){ printf("%s %d, ",COLORS[box[j].colour_index%MAXCOLORS],box[j].product_index); } printf("%s %d",COLORS[box[i-1].colour_index%MAXCOLORS],box[i-1].product_index); printf("\\n\\n"); i = 0; pthread_mutex_unlock(&print_mutex); } } free(box); pthread_exit(0); }
0
#include <pthread.h> int ips[MAX_SERVERS]; int cuotas [MAX_SERVERS]; char *retos[MAX_SERVERS]; int inventario; int capMax; int tiempo_actual; int suministro; FILE *LOG; pthread_mutex_t mutex; int tiempo_respuesta; void *llevar_tiempo(void *arg_tiempo){ int *tiempo= (int*) arg_tiempo; while(*tiempo<480){ if(*tiempo%100 == 0)printf("tiempo : %d \\n",*tiempo); usleep(100000); *tiempo= *tiempo +1; pthread_mutex_lock(&mutex); if(inventario+suministro<capMax){ inventario= inventario + suministro; }else if(inventario!=capMax){ inventario= capMax; fprintf(LOG,"Tanque full: %d minutos \\n",tiempo_actual); } pthread_mutex_unlock(&mutex); } usleep(30000); exit(0); } void tareas_servidor(int argc, char **argv){ char nombre_centro[MAX_LONG]; obtener_argumentos_servidor(argc,argv,nombre_centro,&inventario, &tiempo_respuesta,&suministro,&capMax); char nombre_LOG[MAX_LONG]; sprintf(nombre_LOG,"log_%s.txt",nombre_centro); LOG = fopen(nombre_LOG,"w"); fprintf(LOG,"Inventario inicial: %d litros \\n",inventario); if(inventario==0) fprintf(LOG,"Tanque vacio: 0 minutos \\n"); if(inventario==capMax) fprintf(LOG,"Tanque full: 0 minutos \\n"); fflush(LOG); int ka = 0; while (ka<MAX_SERVERS){ cuotas[ka]=-1; ips[ka]=-1; retos[ka]== 0; ka=ka+1; } pthread_t contador_tiempo; tiempo_actual=0; pthread_create(&contador_tiempo,0,llevar_tiempo,&tiempo_actual); }
1
#include <pthread.h> pthread_mutex_t ma[10]; pthread_mutex_t mi; int i = 0; void *counter() { int x; for (x = 1; x < 10; x++) { pthread_mutex_lock(&mi); i = x; pthread_mutex_unlock(&mi); } return 0; } void *wa(void *aux) { long x = (long) aux; pthread_mutex_lock(&ma[x]); pthread_mutex_unlock(&ma[x]); return 0; } int main() { long x; int idx; pthread_t idk; pthread_t idw[10]; pthread_mutex_init(&mi, 0); for (x = 0; x < 10; x++) { pthread_mutex_init(&ma[x], 0); pthread_create(&idw[x], 0, wa, (void*) x); } pthread_create(&idk, 0, counter, 0); pthread_mutex_lock (&mi); idx = i; pthread_mutex_unlock (&mi); pthread_mutex_lock (&ma[idx]); pthread_mutex_unlock (&ma[idx]); for (x = 0; x < 10; x++) pthread_join(idw[x],0); pthread_join(idk,0); return 0; }
0
#include <pthread.h> void *producer (void *args); void *consumer (void *args); int buf[10]; long head, tail; int full, empty; pthread_mutex_t *mut; pthread_cond_t *notFull, *notEmpty; } queue; queue *queueInit (void); void queueDelete (queue *q); void queueAdd (queue *q, int in); void queueDel (queue *q, int *out); int main () { queue *fifo; pthread_t pro, con; fifo = queueInit (); if (fifo == 0) { fprintf (stderr, "main: Queue Init failed.\\n"); exit (1); } pthread_create (&pro, 0, producer, fifo); pthread_create (&con, 0, consumer, fifo); pthread_join (pro, 0); pthread_join (con, 0); queueDelete (fifo); return 0; } void *producer (void *q) { queue *fifo; int i; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); usleep (100000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); usleep (200000); } return (0); } void *consumer (void *q) { queue *fifo; int i, d; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep(200000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep (50000); } return (0); } queue *queueInit (void) { queue *q; q = (queue *)malloc (sizeof (queue)); if (q == 0) return (0); q->empty = 1; q->full = 0; q->head = 0; q->tail = 0; q->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (q->mut, 0); q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notFull, 0); q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notEmpty, 0); return (q); } void queueDelete (queue *q) { pthread_mutex_destroy (q->mut); free (q->mut); pthread_cond_destroy (q->notFull); free (q->notFull); pthread_cond_destroy (q->notEmpty); free (q->notEmpty); free (q); } void queueAdd (queue *q, int in) { q->buf[q->tail] = in; q->tail++; if (q->tail == 10) q->tail = 0; if (q->tail == q->head) q->full = 1; q->empty = 0; return; } void queueDel (queue *q, int *out) { *out = q->buf[q->head]; q->head++; if (q->head == 10) q->head = 0; if (q->head == q->tail) q->empty = 1; q->full = 0; return; }
1
#include <pthread.h> const unsigned char AD_LASER_A = 0x00; const unsigned char AD_LASER_B = 0x01; const unsigned char AD_LASER_C = 0x02; const unsigned char AD_LASER_D = 0x03; const unsigned char AD_LASER_SUM = 0x04; const unsigned char AD_OSAP = 0x05; const unsigned char AD_FICTION = 0x08; const unsigned char AD_PHASE = 0x0B; const unsigned char AD_ERROR = 0x09; const unsigned char AD_STM = 0x0C; const unsigned char DA_X = 0x04; const unsigned char DA_Y = 0x05; const unsigned char DA_Z = 0x06; short read_AD( unsigned char channel ) { outb(channel, 0x1B0); udelay(5); outb(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); return inw(0x1B0 + 2) & 0xffff; }; static pthread_mutex_t g_ad_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t g_da_mutex = PTHREAD_MUTEX_INITIALIZER; short read_AD_TS( unsigned char channel ) { short value; pthread_mutex_lock(&g_ad_mutex); outb(channel, 0x1B0); udelay(5); outb(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); value = inw(0x1B0 + 2) & 0xffff; pthread_mutex_unlock(&g_ad_mutex); return value; }; short read_AD_N( unsigned char channel, int samplingNum ) { short i, value; int total_value = 0; outb(channel, 0x1B0); udelay(5); for(i = 0; i < samplingNum; i++) { outb(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); value = inw(0x1B0 + 2) & 0xffff; total_value += value; } value = total_value / samplingNum; return value; }; short fast_AD() { outb(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); return inw(0x1B0 + 2) & 0xffff; } short fast_AD_N(int samplingNum) { int total_value = 0; short i, value; for(i = 0; i < samplingNum; i++) { outb(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); value = inw(0x1B0 + 2) & 0xffff; total_value += value; } value = total_value / samplingNum; return value; } short fast_AD_TS() { short value; pthread_mutex_lock(&g_ad_mutex); outb_p(0, 0x1B0 + 1); while( (inb( 0x1B0 ) & 0x01) ); value = inw(0x1B0 + 2) & 0xffff; pthread_mutex_unlock(&g_ad_mutex); return value; } void write_DA_TS( unsigned char channel, unsigned short value ) { pthread_mutex_lock(&g_da_mutex); outw(value, 0x1B0 + 4); inb(0x1B0 + channel); pthread_mutex_unlock(&g_da_mutex); udelay(9); }; void write_DA( unsigned char channel, unsigned short value ) { outw(value, 0x1B0 + 4); inb(0x1B0 + channel); udelay(9); }; void init_Hardware() { iopl(3); outb(0, 0x1B0 + 2); while((inb( 0x1B0 ) & 0x01)); };
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
1
#include <pthread.h> void search_dir_recursively (char *pathname); pthread_mutex_t scandir_mutex = PTHREAD_MUTEX_INITIALIZER, printf_mutex = PTHREAD_MUTEX_INITIALIZER, active_mutex = PTHREAD_MUTEX_INITIALIZER; int num_threads_active = 1; pthread_cond_t threads_active = PTHREAD_COND_INITIALIZER; pthread_t thread; pthread_attr_t detached_attr; char filename [512]; main (int argc, char *argv []) { if (argc < 3) { fprintf (stderr, "\\nUsage: myfind <dir> <filename>\\n\\n"); return 0; } strcpy (filename, argv [2]); if (chdir (argv [1]) != 0) { fprintf (stderr, "\\nUnable to search directory specified\\n\\n"); return 0; } pthread_attr_init (&detached_attr); pthread_attr_setdetachstate (&detached_attr, PTHREAD_CREATE_DETACHED); search_dir_recursively (argv [1]); pthread_mutex_lock (&active_mutex); while (num_threads_active > 0) { pthread_cond_wait (&threads_active, &active_mutex); } } void search_dir_recursively (char *pathname) { struct dirent **entries; int num_entries, i; pthread_mutex_lock (&scandir_mutex); num_entries = scandir (pathname, &entries, 0, 0); pthread_mutex_unlock (&scandir_mutex); for (i = 0; i < num_entries; i++) { struct stat statbuf; char dirfile [1024], *new_dir; if (entries [i] -> d_ino == 0) continue; if (strcmp (entries [i] -> d_name, ".") == 0 || strcmp (entries [i] -> d_name, "..") == 0) continue; sprintf (dirfile, "%s/%s", pathname, entries [i] -> d_name); if (stat (dirfile, &statbuf) == -1 || statbuf.st_mode & S_IFDIR == 0) continue; new_dir = malloc (1024); strcpy (new_dir, dirfile); pthread_mutex_lock (&active_mutex); ++num_threads_active; pthread_mutex_unlock (&active_mutex); pthread_create (&thread, 0, (void *) search_dir_recursively, (void *) new_dir); } for (i = 0; i < num_entries; i++) if (strcmp (entries [i] -> d_name, filename) == 0) { pthread_mutex_lock (&printf_mutex); printf ("%s/%s\\n", pathname, filename); fflush (stdout); pthread_mutex_unlock (&printf_mutex); break; } pthread_mutex_lock (&active_mutex); if (--num_threads_active == 0) pthread_cond_signal (&threads_active); pthread_mutex_unlock (&active_mutex); }
0
#include <pthread.h> int size, filehandle, c, sock2; char buf[100]; struct stat obj; pthread_mutex_t lock_ls; pthread_mutex_t lock_cd; pthread_t main_tid; void* List(void *arg) { pthread_mutex_lock(&lock_ls); system("ls >temps.txt"); stat("temps.txt",&obj); size = obj.st_size; send(sock2, &size, sizeof(int),0); filehandle = open("temps.txt", O_RDONLY); sendfile(sock2,filehandle,0,size); pthread_mutex_unlock(&lock_ls); return 0; } void* Cd(void *arg) { pthread_mutex_lock(&lock_cd); if(chdir(buf+3) == 0) c = 1; else c = 0; pthread_mutex_unlock(&lock_cd); return 0; } int main(int argc,char *argv[]) { int max_number_client = 3; pthread_t tid[max_number_client]; struct sockaddr_in server, client; pthread_mutex_init(&lock_ls, 0); pthread_mutex_init(&lock_cd, 0); int sock1, read_size; int number_client = 0; char command[5], filename[20]; int k, i, len; sock1 = socket(AF_INET, SOCK_STREAM, 0); if(sock1 == -1) { printf("Socket creation failed"); exit(1); } server.sin_port = atoi(argv[1]); server.sin_addr.s_addr = 0; k = bind(sock1,(struct sockaddr*)&server,sizeof(server)); if(k == -1) { printf("Binding error"); exit(1); } k = listen(sock1, max_number_client); if(k == -1) { printf("Listen failed"); exit(1); } while(1) { len = sizeof(client); sock2 = accept(sock1,(struct sockaddr*)&client, &len); if (sock2 < 0) { perror("accept failed"); return 1; } else { number_client = number_client + 1; if(number_client > max_number_client) number_client = 1; } puts("Connection accepted"); while( (read_size = recv(sock2 , buf , 100 , 0)) > 0 ) { sscanf(buf, "%s", command); if(!strcmp(command, "ls")) { pthread_create(&(tid[number_client - 1]), 0, &List, 0); } else if(!strcmp(command, "cd")) { pthread_create(&(tid[number_client - 1]), 0, &Cd, 0); send(sock2, &c, sizeof(int), 0); } } if(read_size == 0) { puts("Client disconnected"); fflush(stdout); } else if(read_size == -1) { perror("recv failed"); } } return 0; }
1
#include <pthread.h> enum fstat { FSTAT_EMPTY, FSTAT_USED, FSTAT_CLOSED, FSTAT_NUM }; struct fd_entry { time_t access_time; enum fstat fstat; pthread_mutex_t lock; }; extern int loglevel; extern FILE *debugfp; static inline void debug_log(const char *action, int fd) { if (loglevel > 0 ) { char name[17] = ""; prctl(PR_GET_NAME, name); fprintf(debugfp, "[pid %d %s] %s %s (%d)\\n", getpid(), name, __FUNCTION__, action, fd); } } struct fd_entry fd_entry[2048]; void mgmt_create_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("create", fd); fde->fstat = FSTAT_USED; fde->access_time = time(0); pthread_mutex_unlock(&fde->lock); } void mgmt_close_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("close", fd); if (fde->fstat != FSTAT_USED) { fprintf(debugfp, "[pid %d] fd %d is in %d stated\\n", getpid(), fd, fde->fstat); abort(); } fde->fstat = FSTAT_CLOSED; pthread_mutex_unlock(&fde->lock); } void mgmt_access_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("access", fd); if (fde->fstat != FSTAT_USED) { fprintf(debugfp, "[pid %d] fd %d is in %d state(not used)\\n", getpid(), fd, fde->fstat); abort(); } fde->access_time = time(0); pthread_mutex_unlock(&fde->lock); } int (*__read)(int fd, char *buf, size_t len); static void init_all_fds() ; static void init_all_fds() { int i; struct fd_entry *fde; struct stat buf; for (i = 0, fde = &fd_entry[0]; i < 2048; ++i, ++fde) { if (fstat(i, &buf) == -1 && errno == EBADF) { fde->fstat = FSTAT_EMPTY; } else { fde->fstat = FSTAT_USED; debug_log("In Used", i); } pthread_mutex_init(&fde->lock, 0); fde->access_time = 0; } }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t){ int i; long my_id = (long)t; for (i=0; i<10; i++){ pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t){ long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]){ int i; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> int arr[1000][1000]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void initArray() { int i = 0; int j = 0; for (i = 0; i < 1000; i++) { for (j = 0; j < 1000; j++) { srand(time(0)); arr[i][j] = rand() % 100; } } } int main() { initArray(); int globalmax = 0; omp_set_num_threads(10); int id; int localmax; int startc; int finishc; int i; int j; { id = omp_get_thread_num(); localmax = arr[0][0]; startc = id * 100; finishc = startc + 100; for (i = startc; i < finishc; i++) { for (j = 0; j < 1000; j++) { if (localmax < arr[i][j]) localmax += arr[i][j]; } } pthread_mutex_lock(&mutex); if (globalmax < localmax) globalmax = localmax; pthread_mutex_unlock(&mutex); } printf("%d", globalmax); }
0
#include <pthread.h> pthread_mutex_t lock_r; pthread_mutex_t lock_s; int sharedData; } buffer; int tot = 0; buffer buf = { .sharedData = 0 }; int store(int item, buffer *pb){ pb->sharedData = item; } int retrieve(buffer *pb){ int item = pb->sharedData; pb->sharedData = 0; return item; } void* producer(void * v){ int j; for (j=0; j<100; j++){ pthread_mutex_lock(& lock_s); store(j, &buf); pthread_mutex_unlock(& lock_r); printf ("producer produce %d\\n", j); usleep(rand()%11); } } void* consumer(void * v){ int j=0; while (j< 100 -1){ pthread_mutex_lock(& lock_r); j = retrieve(&buf); pthread_mutex_unlock(& lock_s); tot = tot + j; usleep(rand()%11); } } int main(int argc, char **argv){ pthread_t th[4]; int i; while (1){ pthread_mutex_init(& lock_s, 0); pthread_mutex_init(& lock_r, 0); pthread_mutex_lock(& lock_r); for (i = 0; i < 4/2; i++){ pthread_create(&th[i], 0, producer, 0); } for (i = 4/2; i < 4; i++){ pthread_create(&th[i], 0, consumer, 0); } for (i = 0; i < 4; i++){ pthread_join(th[i], 0); } pthread_mutex_unlock(& lock_r); printf ("valeur théorique de tot = %d\\n", ((100*(100 -1))/2)*4/2); printf ("valeur réelle de tot = %d\\n", tot); tot = 0; sleep(3); } return 0; }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &condition_mutex ); while( count >= 3 && count <= 6 ) { pthread_cond_wait( &condition_cond, &condition_mutex ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &condition_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_cond ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount2: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
0
#include <pthread.h> static pthread_mutex_t fileMutex = PTHREAD_MUTEX_INITIALIZER; void fileAccessor_enableI2cBus() { pthread_mutex_lock(&fileMutex); { FILE *slots = fopen("/sys/devices/platform/bone_capemgr/slots", "w"); if(slots == 0) { printf("Unable to open file (%s) for writing\\n", "/sys/devices/platform/bone_capemgr/slots"); exit(-1); } int value = fprintf(slots, "%s", "BB-I2C1"); if(value < 0) { printf("Unable to write to file %s\\n", "/sys/devices/platform/bone_capemgr/slots"); exit(-1); } fclose(slots); } pthread_mutex_unlock(&fileMutex); } void fileAccessor_enableCape() { pthread_mutex_lock(&fileMutex); { FILE *slotsFile = fopen("/sys/devices/platform/bone_capemgr/slots", "w"); if(slotsFile == 0) { printf("Unable to open slots file\\n"); exit(-1); } int enableSlot = fprintf(slotsFile, "%s", "BB-ADC"); if(enableSlot < 0) { printf("ERROR: unable to write to file (%s)\\n", "/sys/devices/platform/bone_capemgr/slots"); exit(-1); } fclose(slotsFile); } pthread_mutex_unlock(&fileMutex); } void fileAccessor_getReading(int *a2dReading) { pthread_mutex_lock(&fileMutex); { int counter = 0; FILE *voltage_file; do { voltage_file = fopen("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r"); counter++; struct timespec sleep = {0, 5*1000000}; nanosleep(&sleep, (struct timespec *) 0); } while(voltage_file == 0 && counter < 50); if(voltage_file == 0) { printf("Unable to open voltage_file\\n"); exit(-1); } int reading = fscanf(voltage_file, "%d", a2dReading); if(reading < 0) { printf("Unable to read from voltage file\\n"); exit(-1); } fclose(voltage_file); } pthread_mutex_unlock(&fileMutex); }
1
#include <pthread.h> int sharedVariable = 0; pthread_mutex_t mymutex; pthread_barrier_t barr; void *SimpleThread(void *id){ int num, val; int threadid = (int)id; for(num = 0 ; num < 20 ; num++){ if(random() > 32767/2) usleep(10); val = sharedVariable; printf("***thread %d sees value %d\\n",threadid,val); sharedVariable= val + 1; } pthread_mutex_unlock(&mymutex); val = sharedVariable; printf("Thread %d sees final value %d\\n",threadid, val); pthread_exit(0); } int main(int argc, char *argv[]){ if (argc != 2) { printf("No arguments to show\\n"); return -1; } if (atoi(argv[1]) == 0) { printf("Not a valid input\\n"); return -1; } int number_of_threads = atoi(argv[1]); pthread_t threads[number_of_threads]; void *status; int rc; long t; if(pthread_barrier_init(&barr, 0, number_of_threads)){ printf("Could not create a barrier\\n"); return -1; } pthread_mutex_init(&mymutex, 0); for(t = 0 ; t < number_of_threads ; t++){ printf("IN MAIN: creating thread %ld '%s'\\n", t, *argv); rc = pthread_create(&threads[t], 0, &SimpleThread,(void*)t); if(rc){ printf("ERROR: return code from pthread_create() is %d\\n", rc); exit(-1); } } printf("%d\\n", syscall(342)); for(t = 0 ; t < number_of_threads ; t++){ pthread_join(threads[t], &status); } pthread_mutex_destroy(&mymutex); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t atomic64; pthread_mutex_t atomic32; int64_t atomicRead64(int64_t* i) { pthread_mutex_lock(&atomic64); int64_t r = *i; pthread_mutex_unlock(&atomic64); return r; } void atomicWrite64(int64_t* i, int64_t v) { pthread_mutex_lock(&atomic64); *i = v; pthread_mutex_unlock(&atomic64); return; } int64_t atomicAdd64(int64_t* i, int64_t v) { pthread_mutex_lock(&atomic64); *i += v; int64_t r = *i; pthread_mutex_unlock(&atomic64); return r; } void atomicSafeUnlock64() { if (pthread_mutex_trylock(&atomic64) > 0) pthread_mutex_unlock(&atomic64); } int32_t atomicRead32(int32_t* i) { pthread_mutex_lock(&atomic32); int64_t r = *i; pthread_mutex_unlock(&atomic32); return r; } void atomicWrite32(int32_t* i, int32_t v) { pthread_mutex_lock(&atomic32); *i = v; pthread_mutex_unlock(&atomic32); return; } int32_t atomicAdd32(int32_t* i, int32_t v) { pthread_mutex_lock(&atomic32); *i += v; int32_t r = *i; pthread_mutex_unlock(&atomic32); return r; } void atomicSafeUnlock32() { if (pthread_mutex_trylock(&atomic32) > 0) pthread_mutex_unlock(&atomic32); }
1
#include <pthread.h> static pthread_t alloc_mine; static pthread_mutex_t * alloc_lock; static pthread_cond_t * alloc_clear; static unsigned int alloc_inuse; static void enter_alloc(void) { if (pthread_equal(pthread_self(), alloc_mine)) return; pthread_mutex_lock(alloc_lock); alloc_inuse++; pthread_mutex_unlock(alloc_lock); } static void leave_alloc(void) { if (pthread_equal(pthread_self(), alloc_mine)) return; pthread_mutex_lock(alloc_lock); alloc_inuse--; if (alloc_clear != 0 && alloc_inuse == 0) pthread_cond_signal(alloc_clear); pthread_mutex_unlock(alloc_lock); } static void freeze_alloc(void) { pthread_cond_t * clear; clear = malloc(sizeof(*clear)); pthread_cond_init(clear, 0); pthread_mutex_lock(alloc_lock); alloc_clear = clear; while (alloc_inuse != 0) pthread_cond_wait(alloc_clear, alloc_lock); alloc_clear = 0; alloc_mine = pthread_self(); pthread_cond_destroy(clear); free(clear); } static void resume_alloc(void) { pthread_mutex_unlock(alloc_lock); alloc_mine = 0; } static void reinit_alloc(void) { pthread_mutex_init(alloc_lock, 0); alloc_mine = 0; } static int expected_program(void) { FILE * file; char * line; size_t size; ssize_t read; int match; file = fopen("/proc/self/comm", "r"); line = 0; size = 0; read = getline(&line, &size, file); line[read - 1] = '\\0'; match = strcmp(line, "chrome"); fclose(file); free(line); return match; } static const char headcode_type1[] = { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x55, 0x53, 0x48, 0x89, 0xfb }; static const char headcode_type2[] = { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x55, 0x53, 0x48, 0x89, 0xf3 }; static const char headcode_type3[] = { 0x48, 0x89, 0x5c, 0x24, 0xd0, 0x48, 0x89, 0x6c, 0x24, 0xd8, 0x48, 0x89, 0xfb }; static const char hookcode_part1[] = { 0x48, 0x89, 0x5c, 0x24, 0xf0, 0x48, 0x89, 0x6c, 0x24, 0xf8, 0x48, 0x89, 0xfb, 0x48, 0x89, 0xf5, 0x48, 0x83, 0xec, 0x18, 0x48, 0xb8 }; static const char hookcode_part2[] = { 0xff, 0xd0, 0x48, 0x89, 0xee, 0x48, 0x89, 0xdf, 0x48, 0xb8 }; static const char hookcode_part3[] = { 0xff, 0xd0, 0x48, 0x89, 0xc3, 0x48, 0xb8 }; static const char hookcode_part4[] = { 0xff, 0xd0, 0x48, 0x89, 0xd8, 0x48, 0x8b, 0x6c, 0x24, 0x10, 0x48, 0x8b, 0x5c, 0x24, 0x08, 0x48, 0x83, 0xc4, 0x18, 0xc3 }; static const char hookcode_part5[] = { 0x48, 0xb8 }; static const char hookcode_part6[] = { 0xff, 0xe0 }; static void override_function(void * baseaddr, const void * headcode, size_t headsize) { size_t basesize; void * basepage; void * wrapaddr; void * instruct; if (memcmp(baseaddr, headcode, headsize) != 0) { fprintf(stderr, "%p is not what we expected\\n", baseaddr); _exit(-1); } basesize = ((size_t)baseaddr & 0x0fff) + headsize; basepage = (void *)((size_t)baseaddr & ~0x0fff); wrapaddr = mmap(0, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); mprotect(basepage, basesize, PROT_READ | PROT_WRITE | PROT_EXEC); instruct = wrapaddr; memcpy(instruct, hookcode_part1, sizeof(hookcode_part1)); instruct += sizeof(hookcode_part1); *(void **)instruct = enter_alloc; instruct += sizeof(void *); memcpy(instruct, hookcode_part2, sizeof(hookcode_part2)); instruct += sizeof(hookcode_part2); *(void **)instruct = wrapaddr + 0x60; instruct += sizeof(void *); memcpy(instruct, hookcode_part3, sizeof(hookcode_part3)); instruct += sizeof(hookcode_part3); *(void **)instruct = leave_alloc; instruct += sizeof(void *); memcpy(instruct, hookcode_part4, sizeof(hookcode_part4)); instruct = wrapaddr + 0x60; memcpy(instruct, headcode, headsize); instruct += headsize; memcpy(instruct, hookcode_part5, sizeof(hookcode_part5)); instruct += sizeof(hookcode_part5); *(void **)instruct = baseaddr + headsize; instruct += sizeof(void *); memcpy(instruct, hookcode_part6, sizeof(hookcode_part6)); instruct = baseaddr; memcpy(instruct, hookcode_part5, sizeof(hookcode_part5)); instruct += sizeof(hookcode_part5); *(void **)instruct = wrapaddr; instruct += sizeof(void *); memcpy(instruct, hookcode_part6, sizeof(hookcode_part6)); mprotect(basepage, basesize, PROT_READ | PROT_EXEC); mprotect(wrapaddr, 0x1000, PROT_READ | PROT_EXEC); } static void override_allocator(void) { pthread_mutex_t * lock; if (expected_program()) return; pthread_atfork(freeze_alloc, resume_alloc, reinit_alloc); lock = malloc(sizeof(*lock)); pthread_mutex_init(lock, 0); alloc_mine = 0; alloc_lock = lock; alloc_clear = 0; alloc_inuse = 0; override_function(malloc, headcode_type1, sizeof(headcode_type1)); override_function(calloc, headcode_type2, sizeof(headcode_type2)); override_function(realloc, headcode_type3, sizeof(headcode_type3)); override_function(free, headcode_type3, sizeof(headcode_type3)); }
0
#include <pthread.h> pthread_mutex_t memory_mutex = PTHREAD_MUTEX_INITIALIZER; extern int mmcamera_stacktrace(intptr_t* addrs, size_t max_entries); struct hdr_t { struct hdr_t *prev; struct hdr_t *next; intptr_t bt[15]; int bt_depth; }; static unsigned num; static hdr_t *last; static inline void add(hdr_t *hdr) { hdr->prev = 0; hdr->next = last; if (last) last->prev = hdr; last = hdr; num++; } void *__override_malloc(size_t size) { pthread_mutex_lock(&memory_mutex); hdr_t *hdr = malloc(sizeof(hdr_t)+size); if (hdr) { hdr->bt_depth = mmcamera_stacktrace( hdr->bt, 15); add(hdr); pthread_mutex_unlock(&memory_mutex); return hdr+1; } pthread_mutex_unlock(&memory_mutex); return 0; } void __override_free(hdr_t *hdr) { pthread_mutex_lock(&memory_mutex); if (hdr) { hdr--; if (hdr->prev) hdr->prev->next = hdr->next; else last = hdr->next; if (hdr->next) hdr->next->prev = hdr->prev; free(hdr); num--; } pthread_mutex_unlock(&memory_mutex); } void *__override_calloc(size_t nmemb, size_t size) { pthread_mutex_lock(&memory_mutex); hdr_t *hdr = calloc(1, sizeof(hdr_t)+nmemb*size); if (hdr) { hdr->bt_depth = mmcamera_stacktrace( hdr->bt, 15); add(hdr); pthread_mutex_unlock(&memory_mutex); return hdr + 1; } pthread_mutex_unlock(&memory_mutex); return 0; } void *__override_realloc(void *ptr, size_t size) { pthread_mutex_lock(&memory_mutex); hdr_t *hdr = realloc(ptr, sizeof(hdr_t)+size); if (hdr) { hdr->bt_depth = mmcamera_stacktrace( hdr->bt, 15); add(hdr); pthread_mutex_unlock(&memory_mutex); return hdr + 1; } pthread_mutex_unlock(&memory_mutex); return 0; } static void free_leaked_memory(void) ; static void free_leaked_memory(void) { pthread_mutex_lock(&memory_mutex); hdr_t *del; int cnt; while(last) { del = last; last = last->next; fprintf(stderr, "+++ DELETING LEAKED MEMORY AT %p (%d REMAINING)\\n", del + 1, num) ; for (cnt = 0; cnt < del->bt_depth; cnt++) fprintf(stderr, " %2d %p", del->bt_depth - cnt, (void *)del->bt[cnt]); free(del); num--; } pthread_mutex_unlock(&memory_mutex); }
1
#include <pthread.h> char buf[2][8*16*1024]; int buf_len[2] = {0, 0}; pthread_mutex_t b0mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t b1mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t b0cond = PTHREAD_COND_INITIALIZER; pthread_cond_t b1cond = PTHREAD_COND_INITIALIZER; int done = 0; void *reader() { int readed = 0; int buf_num = 0; while (1) { if (buf_num == 0) { pthread_mutex_lock(&b0mutex); while (buf_len[buf_num] > 0) pthread_cond_wait(&b0cond, &b0mutex); } else { pthread_mutex_lock(&b1mutex); while (buf_len[buf_num] > 0) pthread_cond_wait(&b1cond, &b1mutex); } readed = read(0, buf[buf_num], 8*16*1024); if (readed == -1) { perror("Failed to read data"); exit(1); } buf_len[buf_num] += readed; if (readed == 0) { done = 1; buf[buf_num][readed] = '\\0'; } if (buf_num == 0) { pthread_cond_signal(&b0cond); pthread_mutex_unlock(&b0mutex); } else { pthread_cond_signal(&b1cond); pthread_mutex_unlock(&b1mutex); } if (done) break; buf_num = (buf_num + 1) % 2; } pthread_exit(0); } void *writer() { int written = 0; int buf_num = 0; while (1) { if (buf_num == 0) { pthread_mutex_lock(&b0mutex); while (buf_len[buf_num] == 0) { if (done) { pthread_mutex_unlock(&b0mutex); pthread_exit(0); } pthread_cond_wait(&b0cond, &b0mutex); } } else { pthread_mutex_lock(&b1mutex); while (buf_len[buf_num] == 0) { if (done) { pthread_mutex_unlock(&b1mutex); pthread_exit(0); } pthread_cond_wait(&b1cond, &b1mutex); } } written = write(1, buf[buf_num], buf_len[buf_num]); if (written == -1) { perror("Failed to write data"); exit(1); } buf_len[buf_num] -= written; if (buf_num == 0) { pthread_cond_signal(&b0cond); pthread_mutex_unlock(&b0mutex); } else { pthread_cond_signal(&b1cond); pthread_mutex_unlock(&b1mutex); } if (done) break; if (buf_len[buf_num] == 0) buf_num = (buf_num + 1) % 2; } pthread_exit(0); } int main() { pthread_t r, w; if (pthread_create(&r, 0, reader, 0) != 0) { perror("Failed to create thread"); exit(1); } if (pthread_create(&w, 0, writer, 0) != 0) { perror("Failed to create thread"); exit(1); } if (pthread_join(r, 0) != 0) { perror("Failed to join thread"); exit(1); } if (pthread_join(w, 0) != 0) { perror("Failed to join thread"); exit(1); } if (pthread_mutex_destroy(&b0mutex) != 0) { perror("Failed to destroy mutex"); exit(1); } if (pthread_cond_destroy(&b0cond) != 0) { perror("Failed to destroy condition"); exit(1); } if (pthread_mutex_destroy(&b1mutex) != 0) { perror("Failed to destroy mutex"); exit(1); } if (pthread_cond_destroy(&b1cond) != 0) { perror("Failed to destroy condition"); exit(1); } return 0; }
0
#include <pthread.h> int x = 0; pthread_mutex_t x_mutex; pthread_cond_t x_cond; void *B (void *t) { int boba1, boba2; printf("B: Comecei\\n"); boba1=10000; boba2=-10000; while (boba2 < boba1) boba2++; printf("BYE BYE\\n"); pthread_mutex_lock(&x_mutex); x++; printf("B: x = %d, vai sinalizar a condicao \\n", x); pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *A (void *t) { printf("A: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (x == 0) { printf("A: vai se bloquear...\\n"); pthread_cond_wait(&x_cond, &x_mutex); printf("A: sinal recebido e mutex realocado, x = %d\\n", x); } pthread_mutex_unlock(&x_mutex); printf("HELLO\\n"); pthread_exit(0); } int main(int argc, char *argv[]) { int i; pthread_t threads[3]; pthread_mutex_init(&x_mutex, 0); pthread_cond_init (&x_cond, 0); pthread_create(&threads[0], 0, A, 0); pthread_create(&threads[1], 0, B, 0); pthread_create(&threads[2], 0, A, 0); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("\\nFIM\\n"); pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_exit (0); }
1
#include <pthread.h> struct responce_times { struct timeval start_time; struct timeval end_time; int responce_time; }; int atack_start = 0; char *host = 0; char *path = 0; int *ilist = 0; pthread_mutex_t mutex; struct responce_times *responce_list = 0; int responce_i = 0; void *atack(void *arg) { pid_t pid; pthread_t tid; struct sockaddr_in addr; int sock; char *msg; int l, ret; char buf[1024]; ssize_t recv_size = 0; ssize_t send_size = 0; long user_id = 0; long bukken_id = 0; char *subpath; int i; pid = getpid(); tid = pthread_self(); pthread_mutex_lock( &mutex ); i = responce_i; responce_i++; pthread_mutex_unlock( &mutex ); subpath = malloc(100); if(subpath == 0) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : cannot do malloc().\\n", *((int*)arg), pid, (long)tid); return 0; } srand((unsigned)time(0) + syscall(SYS_gettid)); user_id = rand() % 300000; srand((unsigned)time(0) + syscall(SYS_gettid)); bukken_id = rand() % 50000; sprintf(subpath, "/bukken?user_id=%ld&bukken_id=%ld", user_id, bukken_id); l = strlen(host) + strlen(path) + strlen(subpath) + 64; msg = malloc(l); if(msg == 0) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : cannot do malloc().\\n", *((int*)arg), pid, (long)tid); return 0; } while( ! atack_start ) { usleep(100000); } printf("[%6d] atack. to %s %s%s: pid=%d, tid=%ld\\n", *((int*)arg), host, path, subpath, pid, (long)tid); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr(host); sock = socket(AF_INET, SOCK_STREAM, 0); gettimeofday(&responce_list[i].start_time, 0); ret = connect( sock, (struct sockaddr*)(&addr), sizeof(struct sockaddr_in) ); sprintf(msg, "GET %s%s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n", path, subpath, host); send_size = send(sock, msg, strlen(msg), 0); while(1) { recv_size = recv(sock, buf, 1024, 0); if(recv_size == -1) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : recv() socket error.\\n", *((int*)arg), pid, (long)tid); break; } if(recv_size == 0) { break; } } gettimeofday(&responce_list[i].end_time, 0); close(sock); return arg; } pthread_attr_t make_min_stack() { long default_stack_size = 10485760; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, default_stack_size); size_t stacksize; pthread_attr_getstacksize (&attr, &stacksize); return attr; } int main(int ac, char *av[]) { pid_t pid; pthread_t *tlist; void *result; int thread_num; int status; int i; int count_down; if(ac != 5) { fprintf(stderr, "Usage: %s thread_num count_down hostname path\\n", av[0]); return 1; } pthread_attr_t attr = make_min_stack(); thread_num = atoi(av[1]); if(thread_num <= 0) { fprintf(stderr, "Error: thread_num must be greater than 0.\\n"); return 1; } pthread_mutex_init( &mutex, 0 ); count_down = atoi(av[2]); if(count_down < 0) count_down = 0; host = av[3]; path = av[4]; tlist = malloc(sizeof(pthread_t) * thread_num); ilist = malloc(sizeof(int) * thread_num); responce_list = malloc(sizeof(struct responce_times) * thread_num); pid = getpid(); for(i=0; i<thread_num; i++) { ilist[i] = i; status = pthread_create(tlist+i, &attr, atack, (void*)(ilist+i)); if( status != 0 ) { fprintf(stderr, "Error: cannot create a thread: %d\\n", i); tlist[i] = 0; }else{ } } for(i=count_down; i>0; i--) { fprintf(stderr, "%d\\n", i); sleep(1); } atack_start = 1; for(i=0; i<thread_num; i++) { if(tlist[i] == 0) { continue; } pthread_join(tlist[i], &result); } pthread_mutex_destroy( &mutex ); for(i=0; i<thread_num; i++) { printf("responce time %d = %Lf\\n", i, ((long double)responce_list[i].end_time.tv_sec + (long double)responce_list[i].end_time.tv_usec * 1.0E-6) -((long double)responce_list[i].start_time.tv_sec + (long double)responce_list[i].start_time.tv_usec * 1.0E-6) ); } return 0; }
0
#include <pthread.h> sem_t *empty = 0; sem_t *full = 0; pthread_mutex_t mutex; void *producer(void *arg) { int i; int loops = 4; for (i = 1; i < 4; i++) { pthread_mutex_lock(&mutex); sem_wait(empty); put(i); sem_post(full); pthread_mutex_unlock(&mutex); printf("put %d\\n", i); } pthread_exit(0); } void *consumer(void *arg) { int i, tmp = 0; while (tmp != -1) { pthread_mutex_lock(&mutex); sem_wait(full); tmp = get(); sem_post(empty); pthread_mutex_unlock(&mutex); printf("get: %d\\n", tmp); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t consumer_thread; pthread_t producer_threads[3]; pthread_t producer_thread; pthread_mutex_init(&mutex, 0); empty = sem_open("empty", O_CREAT, 777, 10); full = sem_open("full", O_CREAT, 777, 0); pthread_create(&consumer_thread, 0, consumer, 0); pthread_create(&producer_thread, 0, producer, 0); pthread_exit(0); }
1
#include <pthread.h> int flag = 0; pthread_mutex_t m; pthread_cond_t c; void * func(void *p) { while(1){ pthread_mutex_lock(&m); if(!flag){ pthread_cond_wait(&c,&m); } pthread_mutex_unlock(&m); write(STDOUT_FILENO,p,1); sleep(1); } return 0; } int main() { pthread_t id; pthread_mutex_init(&m,0); pthread_cond_init(&c,0); pthread_create(&id,0,func,"."); pthread_create(&id,0,func,"*"); while(1) { char ch; scanf(" %c",&ch); pthread_mutex_lock(&m); if(ch == 'a') {flag = 1; pthread_cond_signal(&c);} else if(ch == 'b') {flag = 1; pthread_cond_broadcast(&c);} else{flag = 0;} pthread_mutex_unlock(&m); } return 0; }
0
#include <pthread.h>extern void __VERIFIER_assume(int); extern void __VERIFIER_error() ; int block; int busy; int inode; pthread_mutex_t m_inode; pthread_mutex_t m_busy; void *allocator(){ pthread_mutex_lock(&m_inode); if(inode == 0){ pthread_mutex_lock(&m_busy); busy = 1; pthread_mutex_unlock(&m_busy); inode = 1; } block = 1; if (!(block == 1)) ERROR: __VERIFIER_error();; pthread_mutex_unlock(&m_inode); return 0; } void *de_allocator(){ pthread_mutex_lock(&m_busy); if(busy == 0){ block = 0; if (!(block == 0)) ERROR: __VERIFIER_error();; } pthread_mutex_unlock(&m_busy); return ((void *)0); } int main() { pthread_t t1, t2; __VERIFIER_assume(inode == busy); pthread_mutex_init(&m_inode, 0); pthread_mutex_init(&m_busy, 0); pthread_create(&t1, 0, allocator, 0); pthread_create(&t2, 0, de_allocator, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&m_inode); pthread_mutex_destroy(&m_busy); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexsum; void display(char *str) { char *tmp; for(tmp = str;*tmp;tmp++) { write(1,tmp,1); usleep(100); } } void *run(void *param) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutexsum); display(param); pthread_mutex_unlock(&mutexsum); } return; } int main() { int hel, bon; pthread_t hel_id, bon_id; pthread_mutex_init(&mutexsum, 0); hel = pthread_create(&hel_id, 0, run, "Hello world\\n"); bon = pthread_create(&bon_id, 0, run, "Bonjour monde\\n"); if(hel == -1 || bon == -1) { perror("Threads creation error"); exit(-1); } pthread_join(hel_id, 0); pthread_join(bon_id, 0); pthread_mutex_destroy(&mutexsum); return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> void *functionA(); void *functionB(); int var_A, var_B = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int main(){ pthread_t thread1, thread2; int rc1, rc2; printf("\\033[2J"); printf("Deadlock experiment with MUTEX. Does this program lead to deadlock?\\n"); printf("===========================================================\\n"); if( rc1=pthread_create(&thread1, 0, &functionA, 0)){ printf("Error in creating thread %d\\n", rc1 ); } if( rc2=pthread_create(&thread2, 0, &functionB, 0)){ printf("Error in creating thread %d\\n", rc2 ); } pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); exit(0); } void *functionA(){ int x = 0; while(x < 5){ pthread_mutex_lock(&mutex1); printf("I'm T1, just locked mutex1\\n"); pthread_mutex_lock(&mutex2); printf("I'm T1, just locked mutex2\\n"); var_A++; var_B++; printf("I am Thread1: var_A = %d, var_B = %d\\n", var_A, var_B); pthread_mutex_unlock(&mutex2); printf("I'm T1, just freed mutex2\\n"); pthread_mutex_unlock(&mutex1); printf("I'm T1, just freed mutex1\\n"); x++; } pthread_exit(0); } void *functionB(){ int x = 0; while(x < 5){ pthread_mutex_lock(&mutex1); printf("I'm T2, just locked mutex1\\n"); pthread_mutex_lock(&mutex2); printf("I'm T2, just locked mutex2\\n"); var_A++; var_B++; printf("I am Thread2: var_A = %d, var_B = %d\\n", var_A, var_B); pthread_mutex_unlock(&mutex2); printf("I'm T2, just freed mutex2\\n"); pthread_mutex_unlock(&mutex1); printf("I'm T2, just freed mutex1\\n"); x++; } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t count_lock=PTHREAD_MUTEX_INITIALIZER; int count=0; void r1(char *fname, int x, char **bufp) { double temp; int local_count=0; int fd; for (local_count = 0; local_count < 1000; local_count++) { temp = sqrt(x); fd = open(fname,O_CREAT | O_RDWR, 0666); pthread_mutex_lock(&count_lock); count++; pthread_mutex_unlock(&count_lock); *bufp = (char *)malloc(256); sprintf(*bufp, "%d is the square root of %d", temp, x); write(fd, *bufp, strlen(*bufp)); close(fd); free(*bufp); } } void r2(char *fname, int x, char **bufp) { double temp; int i, reads; int start=0, end=1000; int fd; for (i = start; i < end; i++) { fd = open(fname,O_CREAT | O_RDWR, 0666); pthread_mutex_lock(&count_lock); x = x + count; temp = sqrt(x); if (temp == 1) count++; pthread_mutex_unlock(&count_lock); *bufp = (char *)malloc(256); read(fd, *bufp, 24); free(*bufp); close(fd); } } void *base(void *not_used) { int x = 10; char *buf; char fname[22]; sprintf(fname, ".%lX", (long) pthread_self()); r2(fname, x, &buf); unlink(fname); return(0); } extern int main(void) { pthread_t threads[5]; int i; for (i = 0; i < 5; i++) { pthread_create(&(threads[i]), 0, base, 0); } for (i = 0; i < 5; i++) { pthread_join(threads[i], 0); } return 0; }
1
#include <pthread.h> int mediafirefs_releasedir(const char *path, struct fuse_file_info *file_info) { printf("FUNCTION: releasedir. path: %s\\n", path); (void)path; (void)file_info; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "releasedir is a no-op\\n"); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> long mtype; char mtext[128]; } message_buf; char file[][10]={"add 3 4","add 1 5","add 5 5","add 6 5","add 9 2","add 1 7"}; pthread_mutex_t lock; int msqid,msqid1; int flag[5]; void *send(void *name) { if ((msqid = msgget(123,IPC_CREAT|0666)) < 0) { printf("exit\\n"); exit(0); } int buf_length; message_buf sbuf,rbuf; pthread_mutex_lock(&lock); int n = *(int *)name ; sbuf.mtype = n; (void) strcpy(sbuf.mtext,file[n]); buf_length = strlen(sbuf.mtext) + 1 ; if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { } else { printf("send=%s-%d\\n",file[n],n); } pthread_mutex_unlock(&lock); if ((msqid1 = msgget(12,IPC_CREAT|0666)) < 0) { printf("exit\\n"); exit(0); } strcpy(rbuf.mtext,""); if (msgrcv(msqid1, &rbuf, 128, n, 1) < 0) { printf("error\\n"); exit(0); } else { printf("i=%s",rbuf.mtext); printf("\\nbuf_length=%d-%d\\n",strlen(rbuf.mtext),n); } strcpy(rbuf.mtext,"\\n"); } int main(int argc, char const *argv[]) { pthread_t p1[5]; int i=0; int a[5]={1,2,3,4,5}; for ( i = 0; i < 5; i++) { pthread_create(&p1[i],0,send,&a[i]); } for (int j = 0; j < 5; j++) { pthread_join(p1[j],0); } return 0; }
1
#include <pthread.h> struct jc_mode_once { pthread_mutex_t mutex; int once; }; static struct jc_mode_once global_once; static int jc_mode_once_init( struct jc_comm *jcc ) { if (jcc->mode_type) free(jcc->mode_type); jcc->mode_type = strdup("once"); return JC_OK; } static int jc_mode_once_execute( struct jc_comm *jcc ) { pthread_mutex_lock(&global_once.mutex); if (global_once.once == 0) { jcc->getvalue = JC_GET_VALUE; global_once.once = 1; } else jcc->getvalue = JC_IGNORE_VALUE; pthread_mutex_unlock(&global_once.mutex); return JC_OK; } int json_config_mode_once_uninit() { return JC_OK; } int json_config_mode_once_init() { struct json_mode_oper oper; global_once.once = 0; pthread_mutex_init(&global_once.mutex, 0); memset(&oper, 0, sizeof(oper)); oper.json_mode_init = jc_mode_once_init; oper.json_mode_execute = jc_mode_once_execute; return json_mode_module_add("once", 0, &oper); }
0
#include <pthread.h> int counter; pthread_mutex_t mutexcounter; void* updateCounter(void* t){ int i; long tid; tid = (long)t; printf("Thread %ld starting...\\n",tid); pthread_mutex_lock (&mutexcounter); for (i=0; i<100000; i++){ counter++; } pthread_mutex_unlock (&mutexcounter); printf("Thread %ld done.\\n",tid); pthread_exit((void*) t); } int main (int argc, char* argv[]){ pthread_t thread[4]; pthread_attr_t attr; int rc; long t; void *status; counter = 0; pthread_mutex_init(&mutexcounter, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t=0; t<4; t++) { printf("Main: creating thread %ld\\n", t); rc = pthread_create(&thread[t], &attr, updateCounter, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(t=0; t<4; t++) { rc = pthread_join(thread[t], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(-1); } printf("Main: completed join with thread %ld having a status of %ld\\n",t,(long)status); } printf("counter = %d\\n", counter); printf("Main: program completed. Exiting.\\n"); pthread_mutex_destroy(&mutexcounter); pthread_exit(0); }
1
#include <pthread.h> struct data{ int number; int isPrime; int come; long which; }; struct data *list; int counter =0,until; pthread_mutex_t mutex; void *PrimeNumber(void *arg){ int i,a,count=0,num; long id=(long)arg; i=0; pthread_mutex_lock (&mutex); while(i<until-2){ if(list[i].come==1){ pthread_mutex_unlock (&mutex); continue; } list[i].which=id; for(a=2;a<=list[i].number/2;a++){ if(list[i].number%a==0){ count++; pthread_mutex_unlock (&mutex); break; } pthread_mutex_unlock (&mutex); } if((count==0 && list[i].number!= 1 || list[i].number==2) && list[i].number!=0){ list[i].isPrime=1; pthread_mutex_unlock (&mutex); } count=0; i++; pthread_mutex_unlock (&mutex); } pthread_exit(0); } int main(int argc, char *argv[]){ long t; int rc, numT=2; char filename[10]; FILE *fp; if(argc==5){ if(strcmp(argv[1],"-n")==0 && strcmp(argv[3],"-o")==0){ until = atoi(argv[2]); strcpy(filename,argv[4]); }else{ printf("invalid instruction.(ie: -n 100 -o outputfilename)\\n"); exit(1); } }else if(argc==7){ if(strcmp(argv[1],"-n")==0 && strcmp(argv[3],"-t")==0 && strcmp(argv[5],"-o")==0){ until = atoi(argv[2]); numT = atoi(argv[4]); strcpy(filename,argv[6]); }else{ printf("invalid instruction.(ie: -n 100 -t 4 -o outputfilename)\\n"); exit(1); } }else{ printf("There is not enough arguman!!\\n"); exit(0); } fp=fopen(filename,"w"); if(fp == 0) exit(-1); pthread_t threads[numT]; list = malloc(sizeof(struct data)*(until+1)); for(t=0; t<until-2;t++){ list[t].number=t+2; list[t].isPrime=0; list[t].come=0; list[t].which =0; } pthread_mutex_init(&mutex, 0); for(t=0;t<numT;t++){ pthread_create(&threads[t], 0,& PrimeNumber, (void *)t); } for(t=0; t<numT; t++) { pthread_join(threads[t], 0); } for(int i=0;i<=until-2;i++){ if(list[i].isPrime==1){ printf("Thread %d Prime %d\\n",list[i].which,list[i].number); fprintf(fp,"Thread %d Prime %d\\n",list[i].which,list[i].number); }else{ } } fclose(fp); pthread_mutex_destroy(&mutex); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; void* another( void* arg ) { printf( "in child thread, lock the mutex\\n" ); pthread_mutex_lock( &mutex ); sleep( 5 ); pthread_mutex_unlock( &mutex ); } void prepare() { pthread_mutex_lock( &mutex ); } void infork() { pthread_mutex_unlock( &mutex ); } int main() { pthread_mutex_init( &mutex, 0 ); pthread_t id; pthread_create( &id, 0, another, 0 ); sleep( 1 ); int pid = fork(); if( pid < 0 ) { pthread_join( id, 0 ); pthread_mutex_destroy( &mutex ); return 1; } else if( pid == 0 ) { printf( "I anm in the child, want to get the lock\\n" ); pthread_mutex_lock( &mutex ); printf( "I can not run to here, oop...\\n" ); pthread_mutex_unlock( &mutex ); exit( 0 ); } else { pthread_mutex_unlock( &mutex ); wait( 0 ); } pthread_join( id, 0 ); pthread_mutex_destroy( &mutex ); return 0; }
1
#include <pthread.h> sem_t empty_num, product_num; pthread_mutex_t mutex; int buffer[4]; int begin = 0, end = 0, counter = 0, max = 4; void *producer( void *arg ) { printf("pthread producer id : %d run \\n", *(int *)arg ); srand(1); while( 1 ) { sem_wait( &empty_num ); pthread_mutex_lock( &mutex ); buffer[ end ] = rand()%10; counter++; printf("pthread producer id :%d produce at %d and counter is %d\\n", *(int *) arg, buffer[ end ], counter ); end = ++end % max; pthread_mutex_unlock( &mutex ); sem_post( &product_num ); } pthread_exit( 0 ); } void *consumer( void *arg ) { printf("pthread consumer id : %d run \\n", *(int *)arg ); while( 1 ) { sem_wait( &product_num ); pthread_mutex_lock( &mutex ); counter--; printf("pthread consumer id :%d consumer at %d and counter is %d\\n", *(int *) arg, buffer[ begin ], counter ); begin = ++begin % max; pthread_mutex_unlock( &mutex ); sem_post( &empty_num ); } pthread_exit( 0 ); } int main(int argc, char const *argv[]) { pthread_t pthread_consumer[3]; pthread_t pthread_producer[2]; sem_init( &empty_num, 0 , 4 ); sem_init( &product_num, 0 , 0 ); int index = 0, *p = 0 ; for( index = 0; index < 3; index++ ) { p = (int *)malloc( sizeof(int) ); *p = index; if( pthread_create( &pthread_consumer[ index ], 0, producer, p ) != 0) { printf("create consumer error\\n"); return -1; } } for( index = 0; index < 2; index++ ) { p = (int *)malloc( sizeof(int) ); *p = index; if( pthread_create( &pthread_producer[ index ], 0, consumer, p ) != 0) { printf("create consumer error\\n"); return -1; } } for( index = 0; index < 3; index++ ) pthread_join( pthread_consumer[ index ], 0 ); for( index = 0; index < 2; index++ ) pthread_join( pthread_producer[ index ], 0 ); return 0; }
0
#include <pthread.h> pthread_mutex_t flaglock; int flag = 1; void *hello(void *p) { while(1) { pthread_mutex_lock(&flaglock); if(1 != flag) { pthread_mutex_unlock(&flaglock); continue; } pthread_mutex_unlock(&flaglock); printf("hello\\n"); pthread_mutex_lock(&flaglock); flag = 2; pthread_mutex_unlock(&flaglock); } } void *the(void *p) { while(1) { pthread_mutex_lock(&flaglock); if(2 != flag) { pthread_mutex_unlock(&flaglock); continue; } pthread_mutex_unlock(&flaglock); printf("the\\n"); pthread_mutex_lock(&flaglock); flag = 3; pthread_mutex_unlock(&flaglock); } } void *word(void *p) { while(1) { pthread_mutex_lock(&flaglock); if(3 != flag) { pthread_mutex_unlock(&flaglock); continue; } pthread_mutex_unlock(&flaglock); printf("word\\n"); pthread_mutex_lock(&flaglock); flag = 1; pthread_mutex_unlock(&flaglock); } } int main() { pthread_mutex_init(&flaglock, 0); pthread_t t1, t2, t3; pthread_create(&t1, 0, hello, 0); pthread_create(&t2, 0, word, 0); pthread_create(&t3, 0, the, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); }
1
#include <pthread.h> int nitems; int buff[1000000]; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; int nput=0; int nval=0; int nready=0; void *produce(void *), *consume(void *); int main(int argc, char **argv) { int i, nthreads, count[100]; pthread_t tid_produce[100], tid_consume; nitems = 10000; nthreads = 4; for (i = 0; i < nthreads; i++) { count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } pthread_create(&tid_consume, 0, consume, 0); for (i = 0; i < nthreads; i++) { pthread_join(tid_produce[i], 0); printf("count[%d] = %d\\n", i, count[i]); } pthread_join(tid_consume, 0); exit(0); } void * produce(void *arg) { for ( ; ; ) { pthread_mutex_lock(&mutex); if (nput >= nitems) { pthread_mutex_unlock(&mutex); return(0); } buff[nput] = nval; nput++; nval++; nready++; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); *((int *) arg) += 1; } } void * consume(void *arg) { int i; for (i = 0; i < nitems; i++) { pthread_mutex_lock(&mutex); while (nready == 0) pthread_cond_wait(&cond, &mutex); nready--; pthread_mutex_unlock(&mutex); if (buff[i] != i) printf("buff[%d] = %d\\n", i, buff[i]); } return(0); }
0
#include <pthread.h> pthread_mutex_t bloqueo; const int scalar = 2; const int matrix[3][4]= { {1, 5, 6, 7}, {4, 4, 8, 0}, {2, 3, 4, 5} }; int x=3,y=4; int matrixsol[3][4]; int i,j=0; int *mytid; void *multiplicar(void *tid) { mytid=(int *) tid; pthread_mutex_lock (&bloqueo); for (j=0;j<y;j++) matrixsol[*mytid][j]=matrix[*mytid][j]*scalar; pthread_mutex_unlock(&bloqueo); } int main(int argc, char *argv[]){ int tids[3]; pthread_t threads[3]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&bloqueo, 0); for (i=0; i<3; i++) { tids[i] = i; pthread_create(&threads[i], &attr, multiplicar,(void *) &tids[i]); } for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf("Matriz Original\\n"); for (i=0; i<x; i++){ for (j=0; j<y;j++) printf("%d ",matrix[i][j]); printf("\\n"); } printf("\\nLa multiplicamos por 2\\n"); for (i=0; i<x; i++){ for (j=0; j<y;j++) printf("%d ",matrixsol[i][j]); printf("\\n"); } pthread_attr_destroy (&attr); pthread_mutex_destroy (&bloqueo); pthread_exit(0); }
1
#include <pthread.h> sem_t sem; int count = 0; pthread_mutex_t mcount = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t msem = PTHREAD_MUTEX_INITIALIZER; void init() { pthread_mutex_lock( &mcount ); count = 0; pthread_mutex_lock( &msem ); pthread_mutex_unlock( &mcount ); } void wait() { while( 1 ) { pthread_mutex_lock( &mcount ); if ( count > 0 ) { count--; pthread_mutex_unlock( &mcount ); break; } pthread_mutex_unlock( &mcount ); pthread_mutex_lock( &msem ); } } void post() { pthread_mutex_lock( &mcount ); count++; pthread_mutex_unlock( &msem ); pthread_mutex_unlock( &mcount ); } void* thread1( void* arg ) { sleep(1); wait( ); printf( "1st Hello from thread1\\n"); sleep(1); wait( ); wait( ); printf( "2d Hello from thread1\\n"); return 0; } void* thread2( void* arg ) { sleep( 3 ); printf( "Hello from thread2\\n"); post( ); post( ); post( ); return 0; } int main() { init( ); pthread_t id1, id2; pthread_create( &id1, 0, &thread1, 0 ); pthread_create( &id2, 0, &thread2, 0 ); pthread_join( id1, 0 ); pthread_join( id2, 0 ); return 0; }
0
#include <pthread.h> static unsigned long MemoryPoolSize1=1024*1024*32; static unsigned long MemoryPoolSize2=1024*1024*1; static struct rb_root* g_table=0; static pthread_mutex_t g_ipv4status_lock; unsigned long get_ipv4_status(unsigned char*ip) { unsigned long flags; unsigned long status=0; struct my_rbnode*mynode=0; pthread_mutex_lock(&g_ipv4status_lock); mynode=hash_rbtree_search(g_table,ip); status=mynode?mynode->attr.status:multi_ntrie_get_status(ip); pthread_mutex_unlock(&g_ipv4status_lock); return status; } void get_ipv4_all(struct trans_ioctl_ipv4 *attr) { unsigned long flags; struct my_rbnode* mynode=0; pthread_mutex_lock(&g_ipv4status_lock); mynode=hash_rbtree_search(g_table,attr->net); if(mynode){ memcpy(attr, &(mynode->attr), sizeof(struct trans_ioctl_ipv4)); }else{ attr->status = multi_ntrie_get_status(attr->net); attr->lasttime_in=0; attr->lasttime_out=0; attr->bytes_in=0; attr->bytes_out=0; attr->bytesN_in=0; attr->bytesN_out=0; attr->pkts_in=0; attr->pkts_out=0; } pthread_mutex_unlock(&g_ipv4status_lock); } int set_ipv4_status(unsigned char * netprefix,unsigned long prefixlen,unsigned long status) { unsigned long flags; int ret=0; pthread_mutex_lock(&g_ipv4status_lock); if(prefixlen==32){ if(multi_ntrie_get_status(netprefix)==status){ hash_rbtree_delete(g_table,netprefix); }else{ ret=hash_rbtree_insert(g_table,netprefix,status,1 ); } } else{ ret=multi_ntrie_set_status(netprefix,prefixlen,status); } pthread_mutex_unlock(&g_ipv4status_lock); return ret; } static struct trans_ioctl_ipv4 * __get_ipv4_status_and_flow_ptr(unsigned char*ip,unsigned long *status) { struct my_rbnode* mynode=hash_rbtree_search(g_table,ip); if(mynode){ *status=mynode->attr.status; return &(mynode->attr); }else{ *status=multi_ntrie_get_status(ip); return 0; } } unsigned long transfer_test_and_merge_flow4(struct iphdr*ipv4h) { unsigned long flags; struct trans_ioctl_ipv4 *sipnode=0; struct trans_ioctl_ipv4 *dipnode=0; unsigned long scntl; unsigned long dcntl; unsigned long ok_to_go; unsigned short payload_len; pthread_mutex_lock(&g_ipv4status_lock); sipnode = __get_ipv4_status_and_flow_ptr((unsigned char*)&(ipv4h->saddr),&scntl); dipnode = __get_ipv4_status_and_flow_ptr((unsigned char*)&(ipv4h->daddr),&dcntl); ok_to_go=transfer_test_with_status(scntl, dcntl); payload_len=ntohs(ipv4h->tot_len); if(ok_to_go){ if(sipnode){ sipnode->pkts_out ++; sipnode->lasttime_out = time(0); if(dcntl == IPVO_FREE) sipnode->bytesN_out += payload_len; else sipnode->bytes_out += payload_len; } if(dipnode){ dipnode->pkts_in ++; dipnode->lasttime_in = time(0); if(scntl == IPVO_FREE) dipnode->bytesN_in += payload_len; else dipnode->bytes_in += payload_len; } } pthread_mutex_unlock(&g_ipv4status_lock); return ok_to_go; } int print_ipv4_memory_info() { unsigned long flags; pthread_mutex_lock(&g_ipv4status_lock); multi_ntrie_print_memory(); hash_rbtree_print_memory(); pthread_mutex_unlock(&g_ipv4status_lock); return 0; } int cap_ipv4_ss_init(void) { int result; pthread_mutex_init(&g_ipv4status_lock,0); result=multi_ntrie_init(MemoryPoolSize1,MemoryPoolSize2); if(result) goto error1; result=hash_rbtree_init(&g_table); if(result) goto error2; return 0; error2: hash_rbtree_free(&g_table); error1: multi_ntrie_free(); return result; } void cap_ipv4_ss_exit(void) { hash_rbtree_free(&g_table); multi_ntrie_free(); }
1
#include <pthread.h> FILE *io_m5; static struct { pthread_t thread; int (*handler)(); bool handler_started; pthread_cond_t data_avail; } trans = {.handler_started = 0, .data_avail = PTHREAD_COND_INITIALIZER}; void io_m5_init(char const *path) { io_m5 = fopen(path, "r+"); if (!io_m5) { DEBUG("Failed to open %s", path); } return; } void io_m5_clean() { fclose(io_m5); return; } static void *m5_trans_thread(void *arg) { (void)arg; for (;;) { if (trans.handler() == EOF && feof(io_m5)) { return 0; } } } int io_m5_trans_set(int (*handler)()) { trans.handler = handler; return 0; } void io_m5_trans_stop() { pthread_cancel(trans.thread); return; } static struct { unsigned char write : 2; unsigned char clean : 2; unsigned char read : 2; unsigned char new : 1; pthread_mutex_t lock; } tripbuf = {0, 1, 2, 0, PTHREAD_MUTEX_INITIALIZER}; bool io_m5_tripbuf_update() { pthread_mutex_lock(&tripbuf.lock); assert(IN_RANGE(0, tripbuf.write, 2) && IN_RANGE(0, tripbuf.clean, 2) && IN_RANGE(0, tripbuf.read, 2) && IN_RANGE (0, tripbuf.new, 1)); bool updated; if (tripbuf.new) { tripbuf.new = 0; unsigned char tmp = tripbuf.read; tripbuf.read = tripbuf.clean; tripbuf.clean = tmp; updated = 1; } else { updated = 0; } pthread_mutex_unlock(&tripbuf.lock); return updated; } void io_m5_tripbuf_offer_resume() { pthread_mutex_lock(&tripbuf.lock); assert(IN_RANGE(0, tripbuf.write, 2) && IN_RANGE(0, tripbuf.clean, 2) && IN_RANGE(0, tripbuf.read, 2) && IN_RANGE (0, tripbuf.new, 1)); unsigned char tmp = tripbuf.write; tripbuf.write = tripbuf.clean; tripbuf.clean = tmp; tripbuf.new = 1; pthread_cond_broadcast(&trans.data_avail); pthread_mutex_unlock(&tripbuf.lock); if (!trans.handler_started) { trans.handler_started = 1; pthread_create(&trans.thread, 0, m5_trans_thread, 0); } } unsigned char io_m5_tripbuf_write() { return tripbuf.write; } unsigned char io_m5_tripbuf_read() { return tripbuf.read; } void io_m5_trans_trywait() { pthread_mutex_lock(&tripbuf.lock); struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 500L / 1000; ts.tv_nsec += 500L * 1000000L; if (ts.tv_nsec >= 1000000000L) { ts.tv_nsec -= 1000000000L; ts.tv_sec += 1; } for (int rc = 0; !tripbuf.new && rc == 0;) { rc = pthread_cond_timedwait(&trans.data_avail, &tripbuf.lock, &ts); } pthread_mutex_unlock(&tripbuf.lock); }
0
#include <pthread.h> void ports_resume_all_rpcs () { pthread_mutex_lock (&_ports_lock); assert_backtrace (_ports_flags & _PORTS_INHIBITED); _ports_flags &= ~_PORTS_INHIBITED; if (_ports_flags & _PORTS_BLOCKED) { _ports_flags &= ~_PORTS_BLOCKED; pthread_cond_broadcast (&_ports_block); } pthread_mutex_unlock (&_ports_lock); }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo{ int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo* foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return (0); } idx = (((unsigned long)id)% 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_lock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->lock); fp->f_count++; pthread_mutex_unlock(&fp->lock); } struct foo* foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hash_lock); for (fp = fh[HASH[id]]; fp != 0; fp = fp->next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return ; } idx = (((unsigned long)fp->f_id)% 29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destory(&fp->f_lock); free(fp); } else { fp->f_coutn--; pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> int32_t count = 0; pthread_mutex_t lock; pthread_cond_t cond_var; void *IncrementFunction(void* arg) { pthread_mutex_lock(&lock); if (count == 0) { printf("Count in inc: %d\\n", count); pthread_cond_signal(&cond_var); } count += 1; printf("In Increment thread, updated count value: %d\\n", count); printf("Thread ID: %lu \\n", pthread_self()); pthread_mutex_unlock(&lock); pthread_exit(0); } void *DecrementFunction(void* arg) { printf("Count in dec: %d\\n", count); pthread_mutex_lock(&lock); while (count == 0) { printf("Count in dec while: %d\\n", count); if (pthread_cond_wait(&cond_var, &lock)) { printf("Error: Wait Condition Failed to Initialize\\n"); } } count -= 1; printf("In Decrement thread, updated count value: %d\\n", count); printf("Thread ID: %lu \\n", pthread_self()); pthread_mutex_unlock(&lock); pthread_exit(0); } void main(int argc, char *argv[]) { pthread_t thread_to_join, calling_thread; int32_t returnvalue; if (pthread_mutex_init(&lock, 0) != 0) { printf("Error: Mutex init failed\\n"); } if (pthread_cond_init(&cond_var, 0) != 0) { printf("Error: Mutex init failed\\n"); } returnvalue = pthread_create(&calling_thread, 0, IncrementFunction,0); if (returnvalue){ printf("Error: return code from pthread_create() is %d\\n", returnvalue); } returnvalue = pthread_create(&thread_to_join, 0, DecrementFunction,0); if (returnvalue){ printf("Error: return code from pthread_create() is %d\\n", returnvalue); } returnvalue = pthread_join(thread_to_join, 0); if (returnvalue){ printf("Error: Failed, return code from pthread_join() is %d\\n", returnvalue); } returnvalue = pthread_join(calling_thread, 0); if (returnvalue){ printf("Error: Failed, return code from pthread_join() is %d\\n", returnvalue); } int32_t ret1 = pthread_mutex_destroy(&lock); int32_t ret2 = pthread_cond_destroy(&cond_var); if (ret1 || ret2) { printf("Error: Destroy Conditions Failed\\n"); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutexes[2]; pthread_cond_t conditionVars[2]; int permits[2]; pthread_t tids[2]; int data = 0; void * Philosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[i%2]); while (permits[i%2] == 0) { pthread_cond_wait(&conditionVars[i%2],&mutexes[i%2]); } permits[i%2] = 0; pthread_mutex_unlock(&mutexes[i%2]); pthread_mutex_lock(&mutexes[(i+1)%2]); while (permits[(i+1)%2] == 0) { pthread_cond_wait(&conditionVars[(i+1)%2],&mutexes[(i+1)%2]); } permits[(i+1)%2] = 0; pthread_mutex_unlock(&mutexes[(i+1)%2]); printf("philosopher %d thinks \\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[(i+1)%2]); permits[(i+1)%2] = 1; pthread_cond_signal(&conditionVars[(i+1)%2]); pthread_mutex_unlock(&mutexes[(i+1)%2]); pthread_mutex_lock(&mutexes[i%2]); permits[i%2] = 1; pthread_cond_signal(&conditionVars[i%2]); pthread_mutex_unlock(&mutexes[i%2]); return 0; } void * OddPhilosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[(i+1)%2]); while (permits[(i+1)%2] == 0) { pthread_cond_wait(&conditionVars[(i+1)%2],&mutexes[(i+1)%2]); } permits[(i+1)%2] = 0; pthread_mutex_unlock(&mutexes[(i+1)%2]); pthread_mutex_lock(&mutexes[i%2]); while (permits[i%2] == 0) { pthread_cond_wait(&conditionVars[i%2],&mutexes[i%2]); } permits[i%2] = 0; pthread_mutex_unlock(&mutexes[i%2]); printf("philosopher %d thinks\\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[i%2]); permits[i%2] = 1; pthread_cond_signal(&conditionVars[i%2]); pthread_mutex_unlock(&mutexes[i%2]); pthread_mutex_lock(&mutexes[(i+1)%2]); permits[(i+1)%2] = 1; pthread_cond_signal(&conditionVars[(i+1)%2]); pthread_mutex_unlock(&mutexes[(i+1)%2]); return 0; } int main(){ int i; for (i = 0; i < 2; i++) pthread_mutex_init(&mutexes[i], 0); for (i = 0; i < 2; i++) pthread_cond_init(&conditionVars[i], 0); for (i = 0; i < 2; i++) permits[i] = 1; for (i = 0; i < 2 -1; i++){ pthread_create(&tids[i], 0, Philosopher, (void*)(i) ); } pthread_create(&tids[2 -1], 0, OddPhilosopher, (void*)(2 -1) ); for (i = 0; i < 2; i++){ pthread_join(tids[i], 0); } for (i = 0; i < 2; i++){ pthread_mutex_destroy(&mutexes[i]); } for (i = 0; i < 2; i++){ pthread_cond_destroy(&conditionVars[i]); } return 0; }
0
#include <pthread.h> void thinking_init(struct philosopher *ph) { int i; for (i = 0; i < NR; i++) { memset((ph + i)->hands, 0x00, sizeof((ph + i)->hands)); (ph + i)->status = THINKING; (ph + i)->ith = i; printf("%p = status %d %d\\n", (ph + i), (ph + i)->status, (ph + i)->hands[0]); } } void thinking(struct philosopher *ph) { printf("%dth philosopher is thinking now!\\n",ph->ith); } void eating(struct philosopher *ph) { printf("%dth philospher is eating now!\\n",ph->ith); } void hungry(struct philosopher *ph) { printf("%dth philospher is still hungry! S O S...........\\n",ph->ith); } void *try_eating(void *arg) { struct philosopher *ph = (struct philosopher *) arg; int i; srand(time(0)); while (1) { if (count >= NR) count = 0; pthread_mutex_lock(&cp_mutex[count]); i = rand()%NR; thinking(ph+i); pthread_mutex_unlock(&cp_mutex[count]); phv_index[i] = i; if ((ph + phv_index[i])->ith == 0) { pthread_mutex_lock(&cp_mutex[count]); if (cs_shared[NR - 1] == 0 && cs_shared[(ph + phv_index[i])->ith] == 0) { cs_shared[NR - 1] = 1; cs_shared[0] = 1; pthread_mutex_unlock(&cp_mutex[count]); eating(ph + phv_index[i]); pthread_mutex_lock(&cp_mutex[count]); cs_shared[NR - 1] = 0; cs_shared[0] = 0; pthread_mutex_unlock(&cp_mutex[count]); } else { hungry(ph + phv_index[i]); cs_shared[NR - 1] = 0; cs_shared[0] = 0; pthread_mutex_unlock(&cp_mutex[count]); } } else { pthread_mutex_lock(&cp_mutex[1]); if (cs_shared[(ph + phv_index[i])->ith - 1] == 0 && cs_shared[(ph + phv_index[i])->ith] == 0) { cs_shared[(ph + phv_index[i])->ith - 1] = 1; cs_shared[(ph + phv_index[i])->ith] = 1; eating(ph + phv_index[i]); pthread_mutex_unlock(&cp_mutex[1]); pthread_mutex_lock(&cp_mutex[1]); cs_shared[(ph + phv_index[i])->ith - 1] = 0; cs_shared[(ph + phv_index[i])->ith] = 0; pthread_mutex_unlock(&cp_mutex[1]); } else { hungry(ph + phv_index[i]); cs_shared[(ph + phv_index[i])->ith - 1] = 0; cs_shared[(ph + phv_index[i])->ith] = 0; pthread_mutex_unlock(&cp_mutex[1]); } } sleep(1); } } int main() { int i; struct philosopher *ph_p = (struct philosopher *) malloc(sizeof(struct philosopher) * NR); thinking_init(ph_p); for (i = 0; i < NR; i++) { if (pthread_create(&(ph_p + i)->tid, 0, try_eating, ph_p)) { fprintf(stderr, "error creating thread %d.\\n", i); exit(1); } printf("tid:%d\\n", (ph_p + i)->tid); } while (1) sleep(5); return 0; }
1
#include <pthread.h> pthread_mutex_t clock_mutex; int stopsignal = 0; double lastupdate = 0; int clocks_cycle(int nextcycle){ int cnext = cpu_update(nextcycle); int pnext = ppu_update(nextcycle/4)*4; nextcycle = cnext > pnext ? pnext:cnext; if(nextcycle == 0) nextcycle = 1; return nextcycle; } void delay(double time){ static struct timespec waitblock = {0,1}; waitblock.tv_sec = (time_t)time; waitblock.tv_nsec =(long)((time - (int)time)*1000000); pthread_delay_np(&waitblock); } void * clocks_update_main(void * a){ UNUSED(a); int nextup = 4; while(!stopsignal){ if(!nes_loaded){ delay(1); continue; } delay(nextup/(double)SYSTEM_FREQUENCE); pthread_mutex_lock(&clock_mutex); nextup = clocks_cycle(nextup); pthread_mutex_unlock(&clock_mutex); } return 0; } void clocks_stop(){ stopsignal = 1; }
0
#include <pthread.h> pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_spinlock_t spinlock; static void * my_func_pmutex( void *arg){ volatile mytype *p = (mytype *) arg; for( int i = 0; i < 10000000 ; i++){ pthread_mutex_lock(&mut); (*p)++; pthread_mutex_unlock(&mut); } return 0; } static void * my_func_pspinlock( void *arg){ volatile mytype *p = (mytype *) arg; for( int i = 0; i < 10000000 ; i++){ pthread_spin_lock(&spinlock); (*p)++; pthread_spin_unlock(&spinlock); } return 0; } int main( int argc, char** argv){ mytype tmp = 0; pthread_t tinfo[20]; int i; pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED); clock_t time = 0; clock_t start = clock(); for ( i = 0; i < 20; i++){ pthread_create( &tinfo[i], 0 , &my_func_pspinlock, (void*)&tmp ); } for ( i = 0; i < 20; i++){ pthread_join( tinfo[i], 0 ); } clock_t end = clock(); time += end - start; printf("t = %.3f\\n", (double)(time) / CLOCKS_PER_SEC ); return 0; }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc,condp; int buffer = 0; int total_pro = 0; int total_con = 0; void *producer(void *ptr) { while (total_pro < 50){ pthread_mutex_lock(&the_mutex); while (buffer == 10){ pthread_t tid = pthread_self(); printf("FULL! Producer %u is waiting!\\n",(unsigned int)tid); pthread_cond_wait(&condp, &the_mutex); } total_pro++; buffer++; sleep(0.1); pthread_t tid = pthread_self(); printf("Producer %u produce %d \\n",(unsigned int)tid,total_pro); pthread_cond_broadcast(&condc); pthread_cond_broadcast(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { while (total_con < 50){ pthread_mutex_lock(&the_mutex); while (buffer == 0){ pthread_t tid = pthread_self(); printf("EMPTY! Consumer %u is waiting!\\n",(unsigned int)tid); pthread_cond_wait(&condc, &the_mutex); } total_con++; buffer--; sleep(0.1); pthread_t tid = pthread_self(); printf("Consumer %u consume %d \\n", (unsigned int)tid,total_con); pthread_cond_broadcast(&condp); pthread_cond_broadcast(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro1, pro2, pro3, con1, con2; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con1, 0, consumer, 0); pthread_create(&con2, 0, consumer, 0); pthread_create(&pro1, 0, producer, 0); pthread_create(&pro2, 0, producer, 0); pthread_create(&pro3, 0, producer, 0); pthread_join(pro1, 0); pthread_join(pro2, 0); pthread_join(pro3, 0); pthread_join(con1, 0); pthread_join(con2, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); }
0
#include <pthread.h>extern void __VERIFIER_error() ; extern int __VERIFIER_nondet_int(); int idx=0; int ctr1=1, ctr2=0; int readerprogress1=0, readerprogress2=0; pthread_mutex_t mutex; void __VERIFIER_atomic_use1(int myidx) { __VERIFIER_assume(myidx <= 0 && ctr1>0); ctr1++; } void __VERIFIER_atomic_use2(int myidx) { __VERIFIER_assume(myidx >= 1 && ctr2>0); ctr2++; } void __VERIFIER_atomic_use_done(int myidx) { if (myidx <= 0) { ctr1--; } else { ctr2--; } } void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) { *readerstart1 = readerprogress1; *readerstart2 = readerprogress2; } void __VERIFIER_atomic_check_progress1(int readerstart1) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1); if (!(0)) ERROR: __VERIFIER_error();; } return; } void __VERIFIER_atomic_check_progress2(int readerstart2) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1); if (!(0)) ERROR: __VERIFIER_error();; } return; } void *qrcu_reader1() { int myidx; while (1) { myidx = idx; if ( __VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress1 = 1; readerprogress1 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void *qrcu_reader2() { int myidx; while (1) { myidx = idx; if ( __VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress2 = 1; readerprogress2 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void* qrcu_updater() { int i; int readerstart1, readerstart2; int sum; __VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2); if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; } else {} if (sum > 1) { pthread_mutex_lock(&mutex); if (idx <= 0) { ctr2++; idx = 1; ctr1--; } else { ctr1++; idx = 0; ctr2--; } if (idx <= 0) { while (ctr1 > 0); } else { while (ctr2 > 0); } pthread_mutex_unlock(&mutex); } else {} __VERIFIER_atomic_check_progress1(readerstart1); __VERIFIER_atomic_check_progress2(readerstart2); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mutex, 0); pthread_create(&t1, 0, qrcu_reader1, 0); pthread_create(&t2, 0, qrcu_reader2, 0); pthread_create(&t3, 0, qrcu_updater, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> static inline double timestamp(void) { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + tv.tv_usec / 1000000.0; } pthread_mutex_t uber_locks[4]; double uber_times[4]; volatile double inside[4]; volatile double outside[4]; int in_use; static inline double rand_unif() { return (double)rand() / (double)32767; } void drive(int thread_id, int uber_id) { (void) thread_id; double start_time = timestamp(); double sample_x; double sample_y; double res; for (int k = 0; k < 1500000; ++k) { sample_x = rand_unif(); sample_y = rand_unif(); res = pow(sample_x, 2) + pow(sample_y, 2); if (res < 1.0) { inside[uber_id]++; } else { outside[uber_id]++; } } uber_times[uber_id] += (timestamp() - start_time); } void* passenger(void* params) { int me = (int)params; for (int k = 0; k < 3; ++k) { for (int i = 0; i < 4; ++i) { pthread_mutex_lock(&uber_locks[i]); drive(me, i); pthread_mutex_unlock(&uber_locks[i]); break; } } return 0; } void* passenger_better_init(void* params) { int me = (int)params; for (int k = 0; k < 3; ++k) { int uber = (me % 4); pthread_mutex_lock(&uber_locks[uber]); drive(me, uber); pthread_mutex_unlock(&uber_locks[uber]); } return 0; } void* passenger_trylock(void* params) { int me = (int)params; for (int k = 0; k < 3; ++k) { int uber = 0; while (1) { if (pthread_mutex_trylock(&uber_locks[uber]) == 0) { drive(me, uber); pthread_mutex_unlock(&uber_locks[uber]); break; } uber++; uber = uber % 4; } } return 0; } static void print_usage() { printf("Usage: ./uber-pi [PASSENGER_TYPE]\\n"); exit(1); } int main (int argc, char** argv) { srand((unsigned)time(0)); pthread_t threads[8]; if (argc < 2) { print_usage(); } for (int j = 0; j < 4; ++j) { pthread_mutex_init(&uber_locks[j], 0); } double timevar = timestamp(); for (long long i = 0; i < 8; ++i) { if (strcmp(argv[1], "2") == 0) { if (pthread_create(&threads[i], 0, passenger_trylock, (void *)i)) { printf("pthread_create failed\\n"); exit(1); } } else if (strcmp(argv[1], "1") == 0) { if (pthread_create(&threads[i], 0, passenger_better_init, (void *)i)) { printf("pthread_create failed\\n"); exit(1); } } else if (strcmp(argv[1], "0") == 0) { if (pthread_create(&threads[i], 0, passenger, (void *)i)) { printf("pthread_create failed\\n"); exit(1); } } else { print_usage(); } } for (int i = 0; i < 8; ++i) { pthread_join(threads[i], 0); } timevar = (timestamp() - timevar); double inside_sum = 0; double outside_sum = 0; double total_uber_time = 0.0; for (int u = 0; u < 4; ++u) { inside_sum += inside[u]; outside_sum += outside[u]; total_uber_time += uber_times[u]; } double mc_pi = 4.0 * inside_sum/(inside_sum + outside_sum); printf("Average fraction of time Uber drivers were driving: %5.3f\\n", (total_uber_time / 4) / timevar); printf("Value of pi computed was: %f\\n", mc_pi); if (!(fabs(mc_pi - 3.14159265358979323846264338327) < 0.02)) { printf("Your computation of pi was not very accurate, something is probably wrong!\\n"); exit(1); } return 0; }
0
#include <pthread.h> static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t accept_condvar = PTHREAD_COND_INITIALIZER; struct esync { pthread_mutex_t e_mt; pthread_cond_t e_cond; }; static void echoer_callback(int fd, enum ev_type type, void *param) { struct esync *sync = param; pthread_mutex_lock(&sync->e_mt); pthread_cond_signal(&sync->e_cond); pthread_mutex_unlock(&sync->e_mt); } static void * echoer(void *param) { struct esync sync; struct mevent *mev; char buf[128]; int fd = (int)(uintptr_t) param; int len; pthread_mutex_init(&sync.e_mt, 0); pthread_cond_init(&sync.e_cond, 0); pthread_mutex_lock(&sync.e_mt); mev = mevent_add(fd, EVF_READ, echoer_callback, &sync); if (mev == 0) { printf("Could not allocate echoer event\\n"); exit(1); } while (!pthread_cond_wait(&sync.e_cond, &sync.e_mt)) { len = read(fd, buf, sizeof(buf)); if (len > 0) { write(fd, buf, len); write(0, buf, len); } else { break; } } mevent_delete_close(mev); pthread_mutex_unlock(&sync.e_mt); pthread_mutex_destroy(&sync.e_mt); pthread_cond_destroy(&sync.e_cond); } static void acceptor_callback(int fd, enum ev_type type, void *param) { pthread_mutex_lock(&accept_mutex); pthread_cond_signal(&accept_condvar); pthread_mutex_unlock(&accept_mutex); } static void * acceptor(void *param) { struct sockaddr_in sin; pthread_t tid; int news; int s; if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(4321); if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("bind"); exit(1); } if (listen(s, 1) < 0) { perror("listen"); exit(1); } (void) mevent_add(s, EVF_READ, acceptor_callback, 0); pthread_mutex_lock(&accept_mutex); while (!pthread_cond_wait(&accept_condvar, &accept_mutex)) { news = accept(s, 0, 0); if (news < 0) { perror("accept error"); } else { printf("incoming connection, spawning thread\\n"); pthread_create(&tid, 0, echoer, (void *)(uintptr_t)news); } } } main() { pthread_t tid; pthread_create(&tid, 0, acceptor, 0); mevent_dispatch(); }
1
#include <pthread.h> struct acdb_fts { FILE *file_handles[100]; pthread_mutex_t lock; }; static struct acdb_fts *fts_info; static int process_open_request(struct ACPH_FTS_CMD_OPEN_FILE_req *open_req, struct ACPH_FTS_CMD_OPEN_FILE_resp *resp, uint32_t *resp_len, uint32_t *resp_buf_bytes_filled) { int i = 0; for (; i < 100; i++) if (fts_info->file_handles[i] == 0) break; if (i >= 100) { ALOGE("%s: Max number of files reached %d", __func__, 100); return ACPH_FAILURE; } fts_info->file_handles[i] = fopen(open_req->fileName, "wb"); if (!fts_info->file_handles[i]) { ALOGE("%s: failed to open file %s (errno = %d).", __func__, open_req->fileName, errno); return ACPH_ERR_INVALID_FILE_PATH; } if (*resp_len < sizeof(struct ACPH_FTS_CMD_OPEN_FILE_resp)) { ALOGE("%s: can't update the response buffer. len = %d", __func__, *resp_len); fclose(fts_info->file_handles[i]); fts_info->file_handles[i] = 0; return ACPH_FAILURE; } ALOGD("%s: handle %p", __func__, fts_info->file_handles[i]); resp->file_handle_id = i; *resp_buf_bytes_filled = sizeof(struct ACPH_FTS_CMD_OPEN_FILE_resp); return ACPH_SUCCESS; } static int process_write_request(struct ACPH_FTS_CMD_WRITE_FILE_DATA_req *write_req, uint32_t tot_msg_len) { uint8_t * data_ptr; if ((write_req->file_handle_id >= 100) || (write_req->file_handle_id < 0)) { ALOGE("%s: invalid file handle %p.", __func__, write_req->file_handle_id); return ACPH_FAILURE; } if (fts_info->file_handles[write_req->file_handle_id] == 0) { ALOGE("%s: invalid file handle %p:%p.", __func__, write_req->file_handle_id, fts_info->file_handles[write_req->file_handle_id]); return ACPH_FAILURE; } if (tot_msg_len != (write_req->data_length + sizeof(struct ACPH_FTS_CMD_WRITE_FILE_DATA_req))) { ALOGE("%s: invalid date lenth. Total length = %d, Data length = %d", __func__, tot_msg_len, write_req->data_length); return ACPH_FAILURE; } data_ptr = (uint8_t*)write_req; data_ptr += sizeof(struct ACPH_FTS_CMD_WRITE_FILE_DATA_req); if (fwrite(data_ptr, 1, write_req->data_length, fts_info->file_handles[write_req->file_handle_id]) != write_req->data_length) { ALOGE("%s: fwrite failure (errno %d).", __func__, errno); return ACPH_FAILURE; } ALOGD("%s: write %d bytes of data.", __func__, write_req->data_length); return ACPH_SUCCESS; } static int process_close_request(struct ACPH_FTS_CMD_CLOSE_FILE_req *close_req) { if ((close_req->file_handle_id >= 100) || (close_req->file_handle_id < 0)) { ALOGE("%s: invalid file handle %p.", __func__, close_req->file_handle_id); return ACPH_FAILURE; } if (fts_info->file_handles[close_req->file_handle_id] == 0) { ALOGE("%s: invalid file handle %p:%p.", __func__, close_req->file_handle_id, fts_info->file_handles[close_req->file_handle_id]); return ACPH_FAILURE; } if (fclose(fts_info->file_handles[close_req->file_handle_id]) != 0) { ALOGE("%s: fail to close the file %p (errno %d).", __func__, close_req->file_handle_id, errno); return ACPH_FAILURE; } fts_info->file_handles[close_req->file_handle_id] = 0; return ACPH_SUCCESS; } static int32_t acdb_fts_callback(uint16_t cmd, uint8_t *req_buf_ptr, uint32_t req_buf_len, uint8_t *resp_buf_ptr, uint32_t resp_buf_len, uint32_t *resp_buf_bytes_filled) { int ret = ACPH_SUCCESS; pthread_mutex_lock(&fts_info->lock); switch(cmd) { case ACPH_FTS_CMD_OPEN_FILE: ret = process_open_request((struct ACPH_FTS_CMD_OPEN_FILE_req *)req_buf_ptr, (struct ACPH_FTS_CMD_OPEN_FILE_resp *)resp_buf_ptr, &resp_buf_len, resp_buf_bytes_filled); break; case ACPH_FTS_CMD_WRITE_FILE_DATA: ret = process_write_request((struct ACPH_FTS_CMD_WRITE_FILE_DATA_req *)req_buf_ptr, req_buf_len); break; case ACPH_FTS_CMD_CLOSE_FILE: ret = process_close_request((struct ACPH_FTS_CMD_CLOSE_FILE_req *)req_buf_ptr); break; default: ALOGE("%s: unknown command %d.", __func__, cmd); ret = ACPH_FAILURE; break; }; pthread_mutex_unlock(&fts_info->lock); return ret; } int acdb_fts_init(void) { int ret; fts_info = calloc(1, sizeof(struct acdb_fts)); if (fts_info == 0) { ALOGE("%s: memory allocation failed.", __func__); ret = -ENOMEM; goto err_ret; } pthread_mutex_init(&fts_info->lock, 0); ret = acph_register_command(ACPH_FILE_TRANSFER_REG_SERVICEID, acdb_fts_callback); if (ret < 0) { ALOGE("%s: acph register failed error = %d\\n", __func__, ret); goto err_ret; } return 0; err_ret: free (fts_info); return ret; }
0
#include <pthread.h> int saldo_inicial = 500; pthread_mutex_t mutex; int main5(void) { pthread_mutex_init (&mutex, 0); pthread_t h1, h2; pthread_create(&h1, 0, compras_mensuales, "Julieta"); pthread_create(&h2, 0, compras_mensuales, "Leo"); pthread_join(h1, (void **) 0); pthread_join(h2, (void **) 0); return 0; } void compras_mensuales(void * args) { char* nombre = (char*) args; int i = 0; for (; i < (500 / 10); i++) { hacer_compras(10, nombre); if (consulta_saldo() < 0) printf("La cuenta esta en rojo!! El almacenero nos va a matar!\\n"); } } int consulta_saldo() { return saldo_inicial; } void hacer_compras(int monto, const char* nombre) { pthread_mutex_lock(&mutex); int saldoDisponible = consulta_saldo(); if (saldoDisponible>= monto) { printf("Hay saldo suficiente %s esta por comprar.\\n", nombre); usleep(1); comprar(monto); printf("%s acaba de comprar.\\n", nombre); } else printf("No queda suficiente saldo (%d) para que %s haga las compras.\\n", consulta_saldo(), nombre); pthread_mutex_unlock(&mutex); usleep(1); } void comprar(int monto) { saldo_inicial = saldo_inicial - monto; }
1
#include <pthread.h> struct list* next; int data; }Node,*PNode; Node* head; pthread_cond_t procon=PTHREAD_COND_INITIALIZER; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; void initlist(PNode* head) { *head=0; } void* consumer(void* val) { int i=1; while(i) { Node* tmp=0; pthread_mutex_lock(&lock); while(0 == head) { printf("list empty,consumer just waitting...\\n"); pthread_cond_wait(&procon,&lock); } tmp=head; head=tmp->next; tmp->next=0; printf("----------------------------------\\n"); printf("pthread tid: %u\\n",pthread_self()); printf("consumer success, total: %d\\n",i++); printf("----------------------------------\\n"); pthread_mutex_unlock(&lock); free(tmp); tmp=0; } return 0; } void* product(void* val) { initlist(&head); int i=1; while(i) { pthread_mutex_lock(&lock); Node* node=(Node*)malloc(sizeof(Node)); node->data=i; node->next=head; head=node; printf("----------------------------------\\n"); printf("product success,total: %d\\n",i++); printf("----------------------------------\\n"); pthread_mutex_unlock(&lock); sleep(1); pthread_cond_signal(&procon); } return 0; } int main() { void *ret; pthread_t pro,con,con1; pthread_create(&pro,0,product,0); pthread_create(&con,0,consumer,0); pthread_create(&con1,0,consumer,0); pthread_join(pro,&ret); pthread_join(con,&ret); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } extern int __VERIFIER_nondet_int(void); double a[1000]; int count ,num_threads,iterations; double search_no ; pthread_mutex_t count_mutex; void *find_entries(void *tid) { int i, start, *mytid, end; int local_count =0; mytid = (int *) tid; start = (*mytid * iterations); end = start + iterations; printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1); for (i=start; i < end ; i++) { if ( a[i] == search_no ) { local_count ++; } } pthread_mutex_lock (&count_mutex); count = count + local_count; pthread_mutex_unlock (&count_mutex); return 0; } int main(int argc, char *argv[]) { int i,start,ret_count; int *tids; pthread_t * threads; pthread_attr_t attr; printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC): February-2008"); printf("\\n\\t\\t Email : hpcfte@cdac.in"); printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Objective : Finding k matches in the given Array"); printf("\\n\\t\\t..........................................................................\\n"); for (i=0;i<1000;i++){ a[i] = (i %10)+1.0; } search_no = __VERIFIER_nondet_int(); num_threads = 2; if (num_threads > 8) { printf ("Number of thread should be less than or equal to 8\\n"); return 0; } iterations = 1000/num_threads; threads = (pthread_t *) malloc(sizeof(pthread_t) * num_threads); tids = (int *) malloc(sizeof(int) * num_threads); ret_count = pthread_mutex_init(&count_mutex, 0); if(ret_count) { exit(-1); } ret_count=pthread_attr_init(&attr); if(ret_count) { exit(-1); } ret_count = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); if(ret_count) { exit(-1); } for (i=0; i<num_threads; i++) { tids[i] = i; ret_count = pthread_create(&threads[i], &attr,find_entries, (void *) &tids[i]); if(ret_count) { exit(-1); } } for (i=0; i<num_threads; i++) { ret_count = pthread_join(threads[i], 0); if(ret_count) { exit(-1); } } int temp = 0; for (i=0;i<1000;i++){ if (a[i] == search_no) temp++; } __VERIFIER_assert(count == temp); printf("Number of search element found in list Count= %d\\n",count); ret_count = pthread_attr_destroy(&attr); if(ret_count) { exit(-1); } ret_count = pthread_mutex_destroy(&count_mutex); if(ret_count) { exit(-1); } free(threads); free(tids); return 0; }
1
#include <pthread.h> int ringbuffer[(5)]; unsigned reader_unread = 0; unsigned writer_next = 0; pthread_mutex_t ringbuffer_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ringbuffer_written_cond = PTHREAD_COND_INITIALIZER; void process_code(int ch) { int counter; printf("Processing code %d\\n", ch); for(counter=5; counter>0; --counter) { putchar('.'); fflush(stdout); sleep(1); } printf("done.\\n"); } void *reader() { pthread_mutex_lock(&ringbuffer_mutex); for(;;) { if (reader_unread == 0) { pthread_cond_wait(&ringbuffer_written_cond, &ringbuffer_mutex); } if (reader_unread > 0) { int ch; int pos = writer_next - reader_unread; if (pos < 0) pos += (5); ch = ringbuffer[pos]; --reader_unread; if (ch == EOF) break; pthread_mutex_unlock(&ringbuffer_mutex); process_code(ch); pthread_mutex_lock(&ringbuffer_mutex); } } pthread_mutex_unlock(&ringbuffer_mutex); puts("READER THREAD GOT EOF"); return 0; } void *writer() { int ch; do { int overflow = 0; ch = getchar(); pthread_mutex_lock(&ringbuffer_mutex); ringbuffer[writer_next] = ch; ++writer_next; if (writer_next == (5)) writer_next = 0; if (reader_unread < (5)) ++reader_unread; else overflow = 1; pthread_cond_signal(&ringbuffer_written_cond); pthread_mutex_unlock(&ringbuffer_mutex); if (overflow) puts("WARNING: OVERFLOW!"); } while(ch != EOF); puts("WRITER THREAD GOT EOF"); return 0; } int main(int argc, char *argv[]) { pthread_t reader_thread, writer_thread; puts("Starting threads. Type text and press enter, or type ctrl-d at empty line to quit."); pthread_create(&reader_thread, 0, reader, 0); pthread_create(&writer_thread, 0, writer, 0); pthread_join(writer_thread, 0); pthread_join(reader_thread, 0); return 0; }
0
#include <pthread.h> static void worker_state_wait_for_transition(struct benchmark_worker *worker, enum benchmark_worker_state state, enum benchmark_worker_state new_state) { while (worker->state == state) pthread_cond_wait(&worker->cond, &worker->lock); assert(worker->state == new_state); } static void worker_state_transition(struct benchmark_worker *worker, enum benchmark_worker_state old_state, enum benchmark_worker_state new_state) { assert(worker->state == old_state); worker->state = new_state; pthread_cond_signal(&worker->cond); } static void * thread_func(void *arg) { assert(arg != 0); struct benchmark_worker *worker = arg; pthread_mutex_lock(&worker->lock); worker_state_wait_for_transition(worker, WORKER_STATE_IDLE, WORKER_STATE_INIT); if (worker->init) worker->ret_init = worker->init(worker->bench, worker->args, &worker->info); worker_state_transition(worker, WORKER_STATE_INIT, WORKER_STATE_INITIALIZED); worker_state_wait_for_transition(worker, WORKER_STATE_INITIALIZED, WORKER_STATE_RUN); worker->ret = worker->func(worker->bench, &worker->info); worker_state_transition(worker, WORKER_STATE_RUN, WORKER_STATE_END); worker_state_wait_for_transition(worker, WORKER_STATE_END, WORKER_STATE_EXIT); if (worker->exit) worker->exit(worker->bench, worker->args, &worker->info); worker_state_transition(worker, WORKER_STATE_EXIT, WORKER_STATE_DONE); pthread_mutex_unlock(&worker->lock); return 0; } struct benchmark_worker * benchmark_worker_alloc(void) { struct benchmark_worker *w = calloc(1, sizeof (*w)); if (!w) return 0; if (pthread_mutex_init(&w->lock, 0)) goto err_free_worker; if (pthread_cond_init(&w->cond, 0)) goto err_free_worker; if (pthread_create(&w->thread, 0, thread_func, w)) goto err_destroy_cond; return w; err_destroy_cond: pthread_cond_destroy(&w->cond); err_free_worker: free(w); return 0; } void benchmark_worker_free(struct benchmark_worker *w) { pthread_join(w->thread, 0); pthread_cond_destroy(&w->cond); free(w); } int benchmark_worker_init(struct benchmark_worker *worker) { pthread_mutex_lock(&worker->lock); worker_state_transition(worker, WORKER_STATE_IDLE, WORKER_STATE_INIT); worker_state_wait_for_transition(worker, WORKER_STATE_INIT, WORKER_STATE_INITIALIZED); int ret = worker->ret_init; pthread_mutex_unlock(&worker->lock); return ret; } void benchmark_worker_exit(struct benchmark_worker *worker) { pthread_mutex_lock(&worker->lock); worker_state_transition(worker, WORKER_STATE_END, WORKER_STATE_EXIT); worker_state_wait_for_transition(worker, WORKER_STATE_EXIT, WORKER_STATE_DONE); pthread_mutex_unlock(&worker->lock); } int benchmark_worker_run(struct benchmark_worker *worker) { int ret = 0; pthread_mutex_lock(&worker->lock); worker_state_transition(worker, WORKER_STATE_INITIALIZED, WORKER_STATE_RUN); pthread_mutex_unlock(&worker->lock); return ret; } int benchmark_worker_join(struct benchmark_worker *worker) { pthread_mutex_lock(&worker->lock); worker_state_wait_for_transition(worker, WORKER_STATE_RUN, WORKER_STATE_END); pthread_mutex_unlock(&worker->lock); return 0; }
1
#include <pthread.h> sem_t *empty = 0; sem_t *full = 0; pthread_mutex_t mutex; void *producer(void *arg) { int i; int loops = 4; for (i = -4; i <= -1; ++i) { sem_wait(empty); pthread_mutex_lock(&mutex); put(i); pthread_mutex_unlock(&mutex); sem_post(full); printf("put %d\\n", i); } pthread_exit(0); } void *consumer(void *arg) { int i, tmp = 0; while (tmp != -1) { sem_wait(full); pthread_mutex_lock(&mutex); tmp = get(); pthread_mutex_unlock(&mutex); sem_post(empty); printf("get: %d\\n", tmp); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t consumer_thread; pthread_t producer_threads[3]; pthread_t producer_thread; pthread_mutex_init(&mutex, 0); empty = sem_open("empty", O_CREAT, 777, 10); full = sem_open("full", O_CREAT, 777, 0); pthread_create(&consumer_thread, 0, consumer, 0); pthread_create(&producer_thread, 0, producer, 0); pthread_exit(0); }
0
#include <pthread.h> unsigned int g_ulClkRunning = NS_FALSE; unsigned int g_ulElapsedTick = 0; unsigned short g_usFrameNo = MAX_FRM_RANGE-1; unsigned char g_ucSubFrmNo = MAX_SUBFRM_RANGE-1; pthread_t g_tidClk; pthread_attr_t g_attrClk; pthread_cond_t g_condClk; pthread_condattr_t g_condAttrClk; pthread_mutex_t g_mutexClk; pthread_mutexattr_t g_mutexAttrClk; void* ThreadClk(void *arg); unsigned int ClkGetRunningSw() { return g_ulClkRunning; } unsigned int ClkGetElapsedTick() { return g_ulElapsedTick; } void IncSysSubFrameNo() { if (g_ucSubFrmNo == MAX_SUBFRM_RANGE-1) { g_ucSubFrmNo = 0; if (g_usFrameNo == MAX_FRM_RANGE-1) { g_usFrameNo = 0; } else { ++g_usFrameNo; } } else { ++g_ucSubFrmNo; } ++g_ulElapsedTick; } void GetSysFrmNo(unsigned short *pusFrame, unsigned char *pucSubFrame) { *pusFrame = g_usFrameNo; *pucSubFrame = g_ucSubFrmNo; } static int ClkCalcOutTime(unsigned int ulUsDelay, struct timespec *pOutTime) { struct timeval curTime; if (!pOutTime) return NS_ERROR; gettimeofday(&curTime, NS_NULL); pOutTime->tv_sec = curTime.tv_sec; pOutTime->tv_nsec = (curTime.tv_usec + ulUsDelay)*1000; return NS_SUCC; } void ClkInit() { pthread_mutexattr_init(&g_mutexAttrClk); pthread_mutexattr_settype(&g_mutexAttrClk, PLATFORM_MUTEX_RECURSIVE); pthread_mutex_init(&g_mutexClk, &g_mutexAttrClk); pthread_condattr_init(&g_condAttrClk); pthread_condattr_setpshared(&g_condAttrClk, PTHREAD_PROCESS_SHARED); pthread_cond_init(&g_condClk, &g_condAttrClk); pthread_attr_init(&g_attrClk); pthread_attr_setdetachstate(&g_attrClk, PTHREAD_CREATE_DETACHED); g_ulElapsedTick = 0; g_ulClkRunning = CfgGetAutoRunningSw(); if (pthread_create(&g_tidClk, &g_attrClk, ThreadClk, NS_NULL)) { DBG_PRINT("Clock init failed!\\n"); } } void ClkWait() { pthread_mutex_lock(&g_mutexClk); while(!UsrIsAllStatusEqual(USR_IDLE)) pthread_cond_wait(&g_condClk, &g_mutexClk); pthread_mutex_unlock(&g_mutexClk); } void ClkTimedWait() { unsigned int ulUsDelay = 0; struct timespec tsOutTime; ulUsDelay = CfgGetMicroSecondDelay(); ClkCalcOutTime(ulUsDelay, &tsOutTime); pthread_mutex_lock(&g_mutexClk); pthread_cond_timedwait(&g_condClk, &g_mutexClk, &tsOutTime); pthread_mutex_unlock(&g_mutexClk); } void ClkAwake() { pthread_mutex_lock(&g_mutexClk); pthread_cond_signal(&g_condClk); pthread_mutex_unlock(&g_mutexClk); } void ClkAwakeAll() { pthread_mutex_lock(&g_mutexClk); pthread_cond_broadcast(&g_condClk); pthread_mutex_unlock(&g_mutexClk); } void ClkStart() { g_ulClkRunning = NS_TRUE; ClkAwake(); } void ClkStop() { g_ulClkRunning = NS_FALSE; } void ClkClose() { pthread_cancel(g_tidClk); pthread_mutex_destroy(&g_mutexClk); pthread_cond_destroy(&g_condClk); } void* ThreadClk(void *arg) { unsigned short usFrameNo = 0; unsigned char ucSubFrmNo = 0; while(NS_TRUE) { ClkWait(); if (!g_ulClkRunning) continue; IncSysSubFrameNo(); GetSysFrmNo(&usFrameNo, &ucSubFrmNo); UsrSetAllStatus(USR_TX); UsrAwakeAll(); } return NS_NULL; }
1
#include <pthread.h> long buf[100]; int count = 0; pthread_mutex_t lock; pthread_cond_t notfull; pthread_cond_t notempty; int producer_index = 0; int consumer_index = 0 ; void init() { pthread_mutex_init(&lock, 0); pthread_cond_init(&notfull, 0); pthread_cond_init(&notempty, 0); } void * Producer(void * p) { int pid = (int)p; printf("Created Producer[%d] ....\\n", pid); while(1) { pthread_mutex_lock(&lock); while(count==100) { pthread_cond_wait(&notfull, &lock); } int produced = random()%100; buf[producer_index] = produced; producer_index = (producer_index + 1)%100; count++; printf("Producer[%d] produced[%d] %d\\n", pid, producer_index, produced); pthread_mutex_unlock(&lock); pthread_cond_signal(&notempty); } return 0; } void * Consumer(void * c) { int cid = (int)c; printf("Created consumer thread ....\\n"); while(1) { if(consumer_index%10==0) { sleep(1); } pthread_mutex_lock(&lock); while(count==0) { pthread_cond_wait(&notempty, &lock); } int consumed = buf[consumer_index]; count--; consumer_index = (consumer_index + 1) % 100; printf("Consumer[%d] consumed[%d] %d\\n", cid, consumer_index, consumed); pthread_mutex_unlock(&lock); pthread_cond_signal(&notfull); } return 0; } int main (int argc, char *argv []) { pthread_t producer[5], consumer[10]; init(); long int i; for(i=0; i < 5; i++) { if(pthread_create(&producer[i], 0, Producer, (void *)i)!=0) { perror("Producer could not be created!\\n"); exit(0); } } for(i=0; i < 10; i++) { if(pthread_create(&consumer[i], 0, Consumer, (void *)i)!=0) { perror("Consumer thread could not be created!\\n"); exit(0); } } for(i=0; i < 5; i++) { pthread_join(producer[i], 0); } for(i=0; i < 10; i++) { pthread_join(consumer[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; void functionInsideCriticalSection(); void functionInsideCriticalSection() { pthread_mutex_unlock(&(sip->lock)); printf("Value is currently: %i\\n", sip->value); pthread_mutex_lock(&(sip->lock)); } void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; sip->value += functionInsideCriticalSection(); pthread_mutex_unlock(&(sip->lock)); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); return sip->value-3; }
1
#include <pthread.h> void *whatsapp(); void *chat(); void *Producer(); void *Consumer(); int sock,cli; pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER; pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER; pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER; struct sockaddr_in server,client; unsigned int len; char mesg[]="Welcome to socket programming"; char buff[100]; int portn=7793; pthread_t thread1,thread2; pthread_t sunil,rajak; void main() { long t; pthread_create(&thread1,0,whatsapp,(void *)t); pthread_join(thread1, 0); pthread_exit(0); } void *whatsapp(void *threadid) { long tid; tid = (long)threadid; printf("Thread id is %ld\\n",tid); if((sock=socket(AF_INET,SOCK_STREAM,0))==-1) { perror("Socket:"); } server.sin_family=AF_INET; server.sin_port=htons(7796); server.sin_addr.s_addr=INADDR_ANY; bzero(&server.sin_zero,8); len=sizeof(struct sockaddr_in); if((bind(sock, (struct sockaddr *)&server,len))==-1) { perror("bind"); } if((listen(sock, 5))==-1) { perror("listem"); exit(-1); } while(1){ if((cli=accept(sock, (struct sockaddr *)&client,&len))==-1) { perror("accept"); } pthread_create(&thread2,0,chat,cli); } } void *chat(int s) { int cli=(int)s; for(;;) { pthread_create(&sunil,0,Producer,cli); pthread_join(sunil,0); puts(buff); pthread_create(&rajak,0,Consumer,cli); pthread_join(rajak,0); } } void *Producer(int p) { int cli=(int)p; pthread_mutex_lock(&mVar); { recv(cli,buff,sizeof(buff),0); } pthread_mutex_unlock(&mVar); } void *Consumer(int c) { int cli = (int)c; pthread_mutex_lock(&mVar); { if(cli==5) { send(cli,buff,sizeof(buff),0); } } pthread_mutex_unlock(&mVar); }
0
#include <pthread.h> int npos; int buf[10000000], pos=0, val=0; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; sem_t sem; void *fill(void*); void *verify(void*); int main(int argc, char* argv[]) { int k, nthr, count[100], total; pthread_t tidf[100], tidv; if (argc!=3) { printf("usage: %s <nr_pos> <nr_thrs>\\n", argv[0]); return 1; } npos = (atoi(argv[1]))<(10000000)?(atoi(argv[1])):(10000000); nthr = (atoi(argv[2]))<(100)?(atoi(argv[2])):(100); if (sem_init(&sem, 0, 0)== -1) { perror("sem"); return 1; } pthread_create(&tidv, 0, verify, 0); for (k=0;k<nthr;k++) { count[k] = 0; pthread_create(&tidf[k], 0, fill, &count[k]); } total = 0; for (k=0; k<nthr; k++) { pthread_join(tidf[k], 0); printf("count[%d] = %d\\n", k, count[k]); total += count[k]; } printf("Total filled = %d\\n", total); pthread_join(tidv, 0); pthread_mutex_destroy(&mut); sem_destroy(&sem); return 0; } void *fill(void *nr) { while(1) { pthread_mutex_lock(&mut); if (pos >= npos) { pthread_mutex_unlock(&mut); return 0; } buf[pos] = val; pos++; val++; sem_post(&sem); pthread_mutex_unlock(&mut); *(int *)nr += 1; } } void *verify(void *arg) { int k=0; while (1) { sem_wait(&sem); if (buf[k] != k) printf("buf[%d] = %d\\n", k, buf[k]); k++; if (k>=npos) { printf("Verified: %d\\n", k); return 0; } } }
1
#include <pthread.h> void * handle_clnt(void * arg); void send_msg(char * msg, int len); void error_handling(char * msg); int clnt_cnt=0; int clnt_socks[256]; pthread_mutex_t mutx; int main(int argc, char *argv[]) { int serv_sock, clnt_sock; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz; pthread_t t_id; if(argc!=2) { printf("Usage : %s <port>\\n", argv[0]); exit(1); } pthread_mutex_init(&mutx, 0); serv_sock=socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1) error_handling("bind() error"); if(listen(serv_sock, 5)==-1) error_handling("listen() error"); while(1) { clnt_adr_sz=sizeof(clnt_adr); clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz); pthread_mutex_lock(&mutx); clnt_socks[clnt_cnt++]=clnt_sock; pthread_mutex_unlock(&mutx); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); pthread_detach(t_id); printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr)); } close(serv_sock); return 0; } void * handle_clnt(void * arg) { int clnt_sock=*((int*)arg); int str_len=0, i; char msg[100]; while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0) send_msg(msg, str_len); pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) { if(clnt_sock==clnt_socks[i]) { while(i++<clnt_cnt-1) clnt_socks[i]=clnt_socks[i+1]; break; } } clnt_cnt--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void send_msg(char * msg, int len) { int i; pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) write(clnt_socks[i], msg, len); pthread_mutex_unlock(&mutx); } void error_handling(char * msg) { fputs(msg, stderr); fputc('\\n', stderr); exit(1); }
0
#include <pthread.h> pthread_mutex_t mutex; struct _ti { pthread_mutex_t exit; int i; }; int y; void *inc_x(void *x_void_ptr) { ti *x_pt = (ti *)x_void_ptr; while(y < 10000) { pthread_mutex_lock(&mutex); if(y < 10000) { y++; } pthread_mutex_unlock(&mutex); } pthread_mutex_unlock(&(x_pt->exit)); return 0; } int main(int argc, char **argv) { stopwatch_start(); int i, num_threads = 2; ti *x; if(pthread_mutex_init(&mutex, 0)) { fprintf(stderr, "error initializing mutex"); return 3; } y = 0; if(argc > 1) { num_threads = atoi(argv[1]); } x = (ti *) malloc(num_threads * sizeof(ti)); for(i = 0; i < num_threads; i++) { x[i].i = i; pthread_mutex_init(&x[i].exit, 0); pthread_mutex_lock(&x[i].exit); } pthread_t *inc_x_thread; inc_x_thread = (pthread_t *) malloc(num_threads * sizeof(pthread_t)); for(i = 0; i < num_threads; i++) { if(pthread_create(&inc_x_thread[i], 0, inc_x, &x[i])) { fprintf(stderr, "Error creating thread\\n"); return 1; } } for(i = 0; i < num_threads; i++) { pthread_mutex_lock(&x[i].exit); } pthread_mutex_destroy(&mutex); printf("All threads exit\\n"); free(x); free(inc_x_thread); stopwatch_stop(); return 0; }
1
#include <pthread.h> uint32_t bytes_tx; uint32_t bytes_rx; uint64_t total_bytes_tx; uint64_t total_bytes_rx; uint32_t tx_rate; uint32_t rx_rate; uint8_t interval; struct timespec timer; pthread_mutex_t lock; pthread_t stats_thread; } TXRXStats; TXRXStats *stats_create(uint8_t interval) { TXRXStats *s = (TXRXStats *)calloc(1, sizeof(TXRXStats)); if (s == 0) return 0; s->interval = interval; s->timer.tv_sec = interval; pthread_mutex_init(&(s->lock), 0); return s; } void stats_increment(TXRXStats *stats, uint8_t bytes, uint8_t io) { pthread_mutex_lock(&(stats->lock)); switch(io) { case(STATS_TX): stats->bytes_tx += bytes; break; case(STATS_RX): stats->bytes_rx += bytes; break; default: break; } pthread_mutex_unlock(&(stats->lock)); } void stats_retrieve(TXRXStats *stats, uint32_t *tx_rate, uint32_t *rx_rate, uint64_t *total_bytes_tx, uint64_t *total_bytes_rx) { pthread_mutex_lock(&(stats->lock)); if (tx_rate) *tx_rate = stats->tx_rate; if (rx_rate) *rx_rate = stats->rx_rate; if (total_bytes_tx) *total_bytes_tx = stats->total_bytes_tx; if (total_bytes_rx) *total_bytes_rx = stats->total_bytes_rx; pthread_mutex_unlock(&(stats->lock)); } void *monitor_thread(void *stats) { TXRXStats *s = (TXRXStats *)stats; struct timespec t; for(;;) { pthread_mutex_lock(&(s->lock)); s->tx_rate = s->bytes_tx / s->interval; s->rx_rate = s->bytes_rx / s->interval; s->total_bytes_tx += s->bytes_tx; s->total_bytes_rx += s->bytes_rx; s->bytes_tx = 0; s->bytes_rx = 0; t.tv_sec = s->timer.tv_sec; printf("<TX RATE: %d bytes/s>\\n<RX RATE: %d bytes/s>\\n", s->tx_rate, s->rx_rate); pthread_mutex_unlock(&(s->lock)); nanosleep(&t, (struct timespec *)0); } } void stats_start_monitor(TXRXStats *stats) { pthread_create(&(stats->stats_thread), 0, monitor_thread, (void *) stats); } void stats_destroy(TXRXStats *stats){ pthread_mutex_destroy(&(stats->lock)); free(stats); }
0
#include <pthread.h> extern FILE *fileout_dijkstra; extern FILE *filein_dijkstra; extern pthread_mutex_t mutex_print; struct _NODE { int iDist; int iPrev; }; struct _QITEM { int iNode; int iDist; int iPrev; }; QITEM static_queue[500]; int qBegin = -1; int qTail = -1; int AdjMatrix[70][70]; int g_qCount = 0; NODE rgnNodes[70]; int ch; int iPrev, iNode; int i, iCost, iDist; void print_path (NODE *rgnNodes, int chNode) { if (rgnNodes[chNode].iPrev != 9999) { print_path(rgnNodes, rgnNodes[chNode].iPrev); } fprintf (fileout_dijkstra," %d", chNode); } void enqueue_static (int iNode, int iDist, int iPrev) { qTail = (qTail + 1)%500; if (qBegin == qTail) { fprintf(stderr, "The queue is full.\\n"); _exit(0); } static_queue[qTail].iNode = iNode; static_queue[qTail].iDist = iDist; static_queue[qTail].iPrev = iPrev; if (qBegin == -1) qBegin = 0; g_qCount++; } void dequeue_static (int *piNode, int *piDist, int *piPrev) { if(qBegin == -1) { fprintf(stderr, "The queue is empty.\\n"); _exit(0); } *piNode = static_queue[qBegin].iNode; *piDist = static_queue[qBegin].iDist; *piPrev = static_queue[qBegin].iPrev; if (qBegin == qTail) qBegin = qTail = -1; else qBegin = (qBegin+1)%500; g_qCount--; } int qcount (void) { return(g_qCount); } int dijkstra(int chStart, int chEnd) { for (ch = 0; ch < 70; ch++) { rgnNodes[ch].iDist = 9999; rgnNodes[ch].iPrev = 9999; } if (chStart == chEnd) { pthread_mutex_lock(&mutex_print); printf("Shortest path is 0 in cost. Just stay where you are.\\n"); pthread_mutex_unlock(&mutex_print); } else { rgnNodes[chStart].iDist = 0; rgnNodes[chStart].iPrev = 9999; enqueue_static (chStart, 0, 9999); while (qcount() > 0) { dequeue_static (&iNode, &iDist, &iPrev); for (i = 0; i < 70; i++) { if ((iCost = AdjMatrix[iNode][i]) != 9999) { if ((9999 == rgnNodes[i].iDist) || (rgnNodes[i].iDist > (iCost + iDist))) { rgnNodes[i].iDist = iDist + iCost; rgnNodes[i].iPrev = iNode; enqueue_static (i, iDist + iCost, iNode); } } } } pthread_mutex_lock(&mutex_print); fprintf(fileout_dijkstra,"Shortest path is %d in cost. ", rgnNodes[chEnd].iDist); fprintf(fileout_dijkstra,"Path is: "); print_path(rgnNodes, chEnd); fprintf(fileout_dijkstra,"\\n"); pthread_mutex_unlock(&mutex_print); } return 1; } int main_dijkstra(int argc, char *argv[]) { int i,j,k; for (i=0;i<70;i++) for (j=0;j<70;j++) AdjMatrix[i][j]=9999; for (i=0;i<70;i++) { for (j=i+1;j<70;j++) { fscanf(filein_dijkstra,"%d",&k); AdjMatrix[i][j] = k; AdjMatrix[j][i] = k; } } for (i=0,j=70/2;i<70;i++,j++) { j=j%70; dijkstra(i,j); } }
1
#include <pthread.h> FILE *fp1,*fp2; int file_size; char buf[100]; volatile char read_size=0; volatile char buf_ready =0; volatile char end_file =0; pthread_mutex_t pthread_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t pthread_cond = PTHREAD_COND_INITIALIZER; int buf_compare(char *buf1, char *buf2, int size){ int i; for(i=0;i<size;i++){ if(buf1[i] != buf2[i]){ printf("Failed \\n"); return 1; } } return 0; } int compare(FILE *file1, FILE *file2, int file_size) { printf(">>compare\\n"); int readp=0,rest = 0, nread1 =0, nread2 =0; char buf1[1024]; char buf2[1024]; while(1){ if(nread1 = fread(buf1,1024,1,file1) !=1){ printf("fead file1 failed\\n"); break; } if(nread2 = fread(buf2,1024,1,file2) !=1){ printf("fead file2 failed\\n"); break; } readp += 1024; if( buf_compare(buf1, buf2, 1024) == 1){ printf("FAILED\\n"); return 1; } if((file_size - readp) < 1024){ break; } } if(feof(file1)) printf("end of file1 \\n"); if(feof(file2)) printf("end of file2 \\n"); rest = (file_size - readp); if (rest > 1024){ printf("FAILED on file size: rest = %d \\n", rest); return 1; } if(nread1 = fread(buf1,rest,1,file1) != 1) printf("file1 failed \\n"); if(nread2 = fread(buf2,rest,1,file2) !=1) printf("file2 failed \\n"); if(buf_compare(buf1, buf2, rest) == 1){ printf("FAILED\\n"); return 1; }else{ printf("PASS\\n"); } printf("<<compare\\n"); return 0; } void * thread_write(void *arg) { int rp = 0,rest,i; int nWrite =0 ; printf(">>write_thread\\n"); pthread_mutex_lock(&pthread_mutex); while(1){ while(( buf_ready == 0)){ pthread_cond_wait(&pthread_cond, &pthread_mutex); } if(buf_ready == 1){ fwrite(buf,read_size,1,fp2); nWrite += read_size; buf_ready = 0; } if(end_file == 1 ) { break; } } pthread_mutex_unlock(&pthread_mutex); printf("write_thread: total write = %d\\n",nWrite); return 0; } int main(int argc, char * argv[]) { int i,n,rest,nread=0,rp=0,status; struct stat file_stat; if((fp1 = fopen(argv[1],"r+")) == 0) perror("fopen error"); if((fp2 = fopen(argv[2],"w+")) == 0) perror("fopen error"); if(stat(argv[1],&file_stat) != 0) perror("stat error"); printf("file_size = %d\\n",file_stat.st_size); file_size = file_stat.st_size; nread = fread(buf,read_size,1,fp1); while(nread == 1){ fwrite(buf,read_size,1,fp2); nread = fread(buf,read_size,1,fp1); } }
0
#include <pthread.h> static int cant_hilos; static int resto; static pthread_mutex_t lock; static int tarea = -1; static int A[600][600], B[600][600], C[600][600]; struct indices { int i, j; }; void cargarMatrices(); void realizarTarea(indice indiceGral); void *mapearTarea(void *); indice getIndice(int); double getTime(); void imprimirMatrices(); int main(int argc, char *argv[]){ int i, j, k, token; pthread_t *hilos; double t1, t2; if (argc!=2) { fprintf(stderr, "Modo de uso: ./mm1d <cantidad_de_hilos>\\n"); return -1; } cant_hilos=atoi(argv[1]); hilos = (pthread_t *)malloc(sizeof(pthread_t) * (cant_hilos-1)); pthread_mutex_init(&lock, 0); cargarMatrices(); printf("Ok!!\\n\\n"); printf("Multiplicacion ...\\n"); pthread_setconcurrency(cant_hilos); t1=getTime(); for (i=0; i < cant_hilos-1; i++) pthread_create(hilos+i, 0, mapearTarea, 0); mapearTarea(0); for (i=0; i < cant_hilos-1; i++) pthread_join(hilos[i], 0); t2=getTime(); if (600 <= 10 && 600 <= 10 && 600 <= 10){ imprimirMatrices(); } printf("\\n\\nDuracion total de la multilplicacion de matrices %4f segundos\\n", t2-t1); } void cargarMatrices(){ int i, j = 0; for (i=0; i < 600; i++) for (j=0; j < 600; j++) A[i][j] = (j+3) * (i+1); for (i=0; i < 600; i++) for (j=0; j < 600; j++) B[i][j] = i+j; for (i=0; i < 600; i++) for (j=0; j < 600; j++) C[i][j] = 0; } void realizarTarea(indice indiceGral) { int k,j; for(j=0;j<600;j++){ for (k=0; k < 600; k++) C[indiceGral.i][j] += A[indiceGral.i][k] * B[k][j]; } } void *mapearTarea(void *arg) { while (1) { pthread_mutex_lock(&lock); tarea++; pthread_mutex_unlock(&lock); if ( tarea >= 600) return 0; indice indiceGral = getIndice(tarea); realizarTarea(indiceGral); } } indice getIndice(int tarea) { indice indiceGral; indiceGral.i = tarea % 600; return indiceGral; } double getTime() { struct timeval t; gettimeofday(&t, 0); return (double)t.tv_sec+t.tv_usec*0.000001; } void imprimirMatrices() { int i, j = 0; printf("Imprimimos matrices...\\n"); printf("Matriz A\\n"); for (i=0; i < 600; i++) { printf("\\n\\t| "); for (j=0; j < 600; j++) printf("%d ", A[i][j]); printf("|"); } printf("\\n"); printf("Matriz B\\n"); for (i=0; i < 600; i++) { printf("\\n\\t| "); for (j=0; j < 600; j++) printf("%d ", B[i][j]); printf("|"); } printf("\\n"); printf("Matriz C\\n"); for (i=0; i < 600; i++) { printf("\\n\\t| "); for (j=0; j < 600; j++) printf("%d ", C[i][j]); printf("|"); } printf("\\n"); }
1
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t cond; int count; } sema_t; sema_t semaphore = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 1}; void cleanup_mutex(void *arg) { printf("\\tthread %lx: cleanup/unlock_mutex\\n", pthread_self()); pthread_mutex_unlock((pthread_mutex_t *)arg); } void AquireSemaphore(sema_t *ps) { pthread_mutex_lock(&ps->lock); pthread_cleanup_push(cleanup_mutex, &ps->lock); while (ps->count == 0) pthread_cond_wait(&(ps->cond), &(ps->lock)); --ps->count; pthread_cleanup_pop(1); } void ReleaseSemaphore(sema_t *ps) { pthread_mutex_lock(&ps->lock); ++ps->count; pthread_cond_signal(&ps->cond); pthread_mutex_unlock(&ps->lock); } void cleanup_sema(void *arg) { printf("\\tthread %lx: cleanup_sema\\n",pthread_self()); ReleaseSemaphore((sema_t *)arg); } void * thread_routine(void * arg) { int rv; AquireSemaphore(&semaphore); pthread_cleanup_push(cleanup_sema, &semaphore); printf (" thread %lx: sleep\\n", pthread_self()); sleep(1); printf (" thread %lx: waken from sleep\\n", pthread_self()); pthread_cleanup_pop(0); ReleaseSemaphore(&semaphore); } int main(int argc, char* argv[]) { pthread_t thread_id[4]; int i, rv, *status; for (i=0; i<4; i++) { rv = pthread_create (&thread_id[i], 0, thread_routine, 0); check_error(rv, "Create thread"); } sleep (2); for (i=0; i<4; i++) { if ((rv = pthread_cancel (thread_id[i]))== ESRCH) printf("thread %lx dose not exist\\n", thread_id[i]); rv = pthread_join(thread_id[i], (void **)&status); check_error(rv, "Join thread"); if (status==PTHREAD_CANCELED) printf("thread %d canceled %lx\\n", i, thread_id[i]); else printf("thread %d was not canceled\\n", i); } return 0; }
0
#include <pthread.h> static void *zero_thread_main(void *arg); struct zero_threadpool_t *threadpool_init(int number_of_threads) { if (number_of_threads <= 0) { log_err("number_of_threads must greater than 0"); return 0; } struct zero_threadpool_t *pool; pool = (struct zero_threadpool_t*)malloc(sizeof(struct zero_threadpool_t)); if (pool == 0) { log_err("threadpool_init: malloc error"); return 0; } pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * number_of_threads); if (pool == 0) { log_err("threadpool_init: malloc error"); return 0; } int rc; if ((rc = pthread_mutex_init(&(pool->m_lock), 0)) != 0) { log_err("threadpool_init: pthread_mutex_init() error"); return 0; } if ((rc = pthread_cond_init(&(pool->m_cond), 0)) != 0) { log_err("threadpool_init: pthread_cond_init() error"); return 0; } for (int i = 0; i < number_of_threads; i++) { if ((rc = pthread_create(&(pool->threads[i]), 0, zero_thread_main, (void *)pool)) != 0) { log_err("threadpool_init: pthread_create() error"); return 0; } log_info("thread: %d started", i); } pool->wait_queue = (struct zero_task_t *)malloc(sizeof(struct zero_task_t)); if (pool->wait_queue == 0) { log_err("threadpool_init: malloc error"); return 0; } pool->wait_queue->func = 0; pool->wait_queue->args = 0; pool->wait_queue->next_task = 0; pool->size_of_wait_queue = 0; pool->used_of_threads = 0; pool->number_of_threads = number_of_threads; pool->shutdown = 0; return pool; } void threadpool_add(struct zero_threadpool_t *pool, struct zero_task_t *task) { if (task == 0) { log_err("threadpool_add: task == NULL"); exit(1); } int rc; if ((rc = pthread_mutex_lock(&(pool->m_lock))) != 0) { log_err("threadpool_add: pthread_mutex_lock() error"); exit(1); } task->next_task = pool->wait_queue->next_task; pool->wait_queue->next_task = task; pool->size_of_wait_queue++; if ((rc = pthread_cond_signal(&(pool->m_cond))) != 0) { log_err("threadpool_add: pthread_cond_signal() error"); exit(1); } return; } static void *zero_thread_main(void *arg) { if (arg == 0) { log_err("zero_thread_main: arg == NULL"); return 0; } struct zero_threadpool_t *pool = (struct zero_threadpool_t*)arg; while (1) { pthread_mutex_lock(&(pool->m_lock)); while (pool->size_of_wait_queue == 0 && !(pool->shutdown)) { pthread_cond_wait(&(pool->m_cond), &(pool->m_lock)); } if (pool->shutdown) { break; } struct zero_task_t *task = pool->wait_queue->next_task; pool->wait_queue->next_task = task->next_task; pool->size_of_wait_queue--; pthread_mutex_unlock(&(pool->m_lock)); (*(task->func))(task->args); free(task); } pthread_mutex_unlock(&(pool->m_lock)); pthread_exit(0); return 0; } void threadpool_free(struct zero_threadpool_t *pool) { if (pool->threads) free(pool->threads); struct zero_task_t *task; while(pool->wait_queue->next_task != 0) { task = pool->wait_queue->next_task; pool->wait_queue->next_task = pool->wait_queue->next_task->next_task; free(task); } } void threadpool_destroy(struct zero_threadpool_t *pool) { pthread_mutex_lock(&(pool->m_lock)); do { if (pool->shutdown) break; pool->shutdown = 1; pthread_cond_broadcast(&(pool->m_cond)); pthread_mutex_unlock(&(pool->m_lock)); for (int i = 0; i < pool->number_of_threads; i++) { pthread_join(pool->threads[i], 0); log_info("thread %d exit", i); } } while(0); pthread_mutex_destroy(&(pool->m_lock)); pthread_cond_destroy(&(pool->m_cond)); threadpool_free(pool); }
1
#include <pthread.h> struct global_info { int *X; int *Y; int Sum; int Len; } data; pthread_mutex_t lock; int thread; void * dotprod (void *arg) { int i; int sum = 0; long tid = (long) arg; for (i = tid; i < data.Len; i+=thread) { sum += (data.X[i] * data.Y[i]); } pthread_mutex_lock (&lock); data.Sum += sum; pthread_mutex_unlock (&lock); pthread_exit (0); } int main (int argc, char *argv[]) { if(argc != 4) { printf("Requires array size, range of random numbers and number of threads as argument\\n"); exit(1); } int arr_size = atoi (argv[1]), range = atoi (argv[2]); thread = atoi (argv[3]); long i; seed (); data.X = malloc (sizeof(int) * arr_size); data.Y = malloc (sizeof(int) * arr_size); data.Sum = 0; data.Len = arr_size; getArray (data.X, arr_size, range); getArray (data.Y, arr_size, range); pthread_t *threads = malloc (sizeof(pthread_t) * thread); pthread_attr_t attr; pthread_mutex_init (&lock, 0); pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < thread; i++) { pthread_create (&threads[i], &attr, dotprod, (void *) i); } pthread_attr_destroy (&attr); void *status; for (i = 0; i < thread; i++) { pthread_join (threads[i], &status); } pthread_mutex_destroy (&lock); printf ("The dot product is %d\\n",data.Sum); free(threads); free(data.X); free(data.Y); pthread_exit (0); }
0
#include <pthread.h> pthread_mutex_t a; pthread_mutex_t c; pthread_mutex_t f; pthread_mutex_t g; int k; int j; void* fn1(void * args){ pthread_mutex_lock(&a);; if( k == 25 ){ j = 1; pthread_mutex_unlock(&f);; pthread_mutex_lock(&g);; if( j ) printf("hola\\n"); else printf("adios\\n"); } else { pthread_mutex_lock(&c);; } } void* fn2(void * args){ pthread_mutex_unlock(&a);; if( k == 12 ){ j = 1; pthread_mutex_unlock(&c);; } else { j = 0; pthread_mutex_lock(&f);; j = j+1; pthread_mutex_unlock(&g);; } } int main() { pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, &fn1, 0); pthread_create(&thread2, 0, &fn2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mux; pthread_cond_t cond; int is_locked; int wait_count; int usage_count; } _EVENT; int _tr50_event_create(void **handle) { _EVENT *evt; if (handle == 0) { return ERR_TR50_BADHANDLE; } if ((*handle = _memory_malloc(sizeof(_EVENT))) == 0) { return ERR_TR50_MALLOC; } _memory_memset(*handle, 0, sizeof(_EVENT)); evt = *handle; evt->is_locked = TRUE; if ((pthread_mutex_init(&evt->mux, 0)) != 0) { return ERR_TR50_OS; } if ((pthread_cond_init(&evt->cond, 0)) != 0) { return ERR_TR50_OS; } return 0; } int _tr50_event_wait(void *handle) { _EVENT *evt = handle; int ret; struct timespec tc; int ret2; if (handle == 0) { return ERR_TR50_BADHANDLE; } ++evt->usage_count; if ((ret = pthread_mutex_lock(&evt->mux)) != 0) { return ERR_TR50_OS; } while (evt->is_locked) { ++evt->wait_count; if ((ret = pthread_cond_wait(&evt->cond, &evt->mux)) != 0) { --evt->wait_count; pthread_mutex_unlock(&evt->mux); return ERR_TR50_OS; } --evt->wait_count; } if ((ret = pthread_mutex_unlock(&evt->mux)) != 0) { return ERR_TR50_OS; } return 0; } int _tr50_event_signal(void *handle) { _EVENT *evt = handle; if (handle == 0) { return ERR_TR50_BADHANDLE; } if ((pthread_mutex_lock(&evt->mux)) != 0) { return ERR_TR50_OS; } evt->is_locked = FALSE; if ((pthread_cond_broadcast(&evt->cond)) != 0) { return ERR_TR50_OS; } if ((pthread_mutex_unlock(&evt->mux)) != 0) { return ERR_TR50_OS; } return 0; } int _tr50_event_delete(void *handle) { _EVENT *evt = handle; int ret; if (handle == 0) { return ERR_TR50_TIMEOUT; } if ((ret = pthread_cond_destroy(&evt->cond)) != 0) { log_should_not_happen("event_delete(): pthread_cond_destroy failed[%d]\\n", ret); } if ((ret = pthread_mutex_destroy(&evt->mux)) != 0) { log_should_not_happen("event_delete(): pthread_mutex_destroy failed[%d]\\n", ret); } _memory_free(handle); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init( void ) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex,&attr); pthread_mutexattr_destroy(&attr); } int my_getenv2( char *buf,const char *name, int buflen) { int namelen,envirlen,i; extern char **environ; pthread_once(&init_done,thread_init); namelen = strlen(name); pthread_mutex_lock(&mutex); for (i = 0; environ[i] != 0;i++){ if (strncmp(name,environ[i],namelen) == 0 && environ[i][namelen] == '='){ envirlen = strlen(&environ[i][namelen+1]); if (envirlen >= buflen){ pthread_mutex_unlock(&mutex); return ENOSPC; } strcpy(buf,&environ[i][namelen+1]); pthread_mutex_unlock(&mutex); return 0; } } pthread_mutex_unlock(&mutex); return ENOENT; } void * thr1_func( void *arg ) { char buf[1024]; my_getenv2(buf,"HOME",1024); printf("%s\\n",buf); sleep(1); pthread_exit((void *)0); } void * thr2_func( void *arg ) { char buf[1024]; my_getenv2(buf,"PATH",1024); printf("%s\\n",buf); sleep(1); pthread_exit((void *)0); } int main(void) { pthread_t tid1,tid2; for (;;){ pthread_create(&tid1,0,thr1_func,0); pthread_create(&tid2,0,thr2_func,0); } exit(0); }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int reacteur =0; int nbH, nbO, nbE; void* eau(void* arg){ int deltar = arg; while(1 && nbO >= 0 && nbH >= 0){ pthread_mutex_lock(&lock); fflush(stdout); if(reacteur==5){ if(nbE == 0){ printf(" No more Reaction!\\n"); nbO = -1; nbH = -1; exit(1); } else{ printf("reaction begins...\\n"); reacteur=0; nbE--; usleep(deltar); printf("...drop!...\\n"); } } else pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); } } void* oxygene(void* arg){ int deltao = arg; while(1 && (nbH >= 0 && nbO >= 0)){ pthread_mutex_lock(&lock); if(reacteur%2!=1 && reacteur<=5){ if(nbO == 0){ printf(" No more Oxygen!\\n"); nbH = -1; nbO = -1; exit(1); } else{ printf("O-atom produced..\\n"); reacteur++; nbO--; usleep(deltao); printf("O-atom entered...\\n"); } } pthread_cond_wait(&cond,&lock); pthread_mutex_unlock(&lock); } } void* hydrogene(void* arg){ int deltah = arg; while(1 && (nbH >= 0 && nbO >= 0)){ pthread_mutex_lock(&lock); if(reacteur<4){ if(nbH == 0){ printf(" No more Hydrogen!\\n"); nbO = -1; nbH = -1; exit(1); } else{ printf("H-atom produced...\\n"); reacteur=reacteur+2; nbH--; usleep(deltah); printf("H-atom entered...\\n"); } } pthread_cond_wait(&cond,&lock); pthread_mutex_unlock(&lock); } } int main(int argc, char **args){ if(argc<7){ printf("\\n Usage: %s <nb H> <deltah> <nb O> <deltao> <nb E> <deltar>\\n\\n",args[0]); return 0; } pthread_t HY; pthread_t OX; pthread_t RE; nbH = atoi(args[1]); nbO = atoi(args[3]); nbE = atoi(args[5]); int deltah = atoi(args[2]); int deltao = atoi(args[4]); int deltar = atoi(args[6]); pthread_create(&HY,0,hydrogene,(void*) deltah); pthread_create(&OX,0,oxygene,(void*) deltao); pthread_create(&RE,0,eau,(void*) deltar); pthread_join(HY,0); pthread_join(OX,0); pthread_join(RE,0); return 0; }
0
#include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } printf("Hello from main\\n"); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Exit from main\\n"); return 0; exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\\n",counter); pthread_mutex_unlock( &mutex1 ); }
1
#include <pthread.h> static pthread_mutex_t *_newMutex(void); pthread_mutex_t *Posix_CreateMutex(void) { pthread_mutex_t *retval = _newMutex(); if(pthread_mutex_init(retval, 0) != 0) { free(retval); return 0; } return retval; } void Posix_DestroyMutex(pthread_mutex_t *mutex) { if(!mutex) { return; } if(pthread_mutex_destroy(mutex)) { fprintf(stderr, "mutex %p busy\\n", (void *) mutex); assert(0); return; } free(mutex); return; } int Posix_TryLockMutex(pthread_mutex_t *mutex) { if(!mutex) { return -1; } if(pthread_mutex_trylock(mutex) == EBUSY) { return -1; } return 0; } void Posix_LockMutex(pthread_mutex_t *mutex) { if(!mutex) { return; } pthread_mutex_lock(mutex); } void Posix_UnlockMutex(pthread_mutex_t *mutex) { if(!mutex) { return; } pthread_mutex_unlock(mutex); } static pthread_mutex_t *_newMutex(void) { pthread_mutex_t *retval = malloc(sizeof *retval); return retval; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int avail = 0; void *fun(void *arg) { int i; int counter = atoi( arg); for ( i=0; i< counter; i++){ pthread_mutex_lock(&mutex); printf("%d\\n", i); avail++; pthread_mutex_unlock(&mutex); } return 0; } int main( int argc, char *argv[]) { int i; pthread_t tid; int total_requested; int unit; int token; total_requested = 0; for (i=0; i<argc; i++){ total_requested = total_requested + atoi(argv[i]); pthread_create(&tid, 0, fun, argv[i]); } unit = 0; token = 0; for (;;){ pthread_mutex_lock(&mutex); while( avail>0 ){ unit++; avail--; printf("unit=%d\\n", unit); token = (unit >= total_requested)? 1:0; } pthread_mutex_unlock(&mutex); if(token) break; } return 0; }
1
#include <pthread.h> pthread_mutex_t lock; void execute_operations(void * arg) { FILE *fptr; char error = 0; char opened_in_read = 1; char buf[12000]; char buf2[500]; int fd; ssize_t ret_read, ret_write; char * filename1 = "/mnt/trfs/bigDirectoryName/abracadabra.txt"; char * filename2 = "/mnt/trfs/bigDirectoryName/abracadabra2.txt"; mkdir("/mnt/trfs/bharathkrishna",0644); link("/mnt/trfs/abc.txt","/mnt/trfs/efg.txt"); rename("/mnt/trfs/abc.txt","/mnt/trfs/xyz.txt"); pthread_mutex_lock(&lock); int fd2 = open("content.txt", O_RDONLY, 0644); read(fd2, &buf, 12000); close(fd2); strcpy(buf2, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); fd = open(filename1 , O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd == -1) { perror ("open1"); return; } printf("READ BUF = %s", buf); ret_write = write(fd, &buf, strlen(buf)); close(fd); fd = open(filename1, O_RDONLY | O_CREAT , 0644); if (fd == -1) { perror ("open"); return; } ret_read = read(fd, &buf, ret_write); close(fd); fd = open(filename2, O_RDWR | O_CREAT , 0644); ret_write = write(fd, &buf2, strlen(buf2)); close(fd); printf("ret_write= %d",ret_write); fd = open(filename2, O_RDONLY, 0644); if (fd == -1) { perror ("open"); return; } ret_read = read(fd, &buf2, ret_write); printf("read : %s \\n", buf2); close(fd); pthread_mutex_unlock(&lock); } void main() { pthread_t pth1; pthread_t pth2; pthread_t pth3; int i = 0; while (i < 30 ) { usleep(1); printf("main() is running...\\n"); ++i; } execute_operations(0); }
0
#include <pthread.h> void *foo10Secs(void *data) { assert(data == 0); char *arr = malloc(sizeof(int)* (1024 * 60)); for(int i = 0; i < (1024 * 60); i++) arr[i] = i; for(int i = 0; i < (1024 * 60); i++) for(int j = 0; j < (1024 * 60); j++) if(arr[i] == 255) printf("bug\\n"); free(arr); printf("Thread has finished executing\\n"); return 0; } void* fooCounter(void *data) { assert(data == 0); printf("\\n"); sleep((rand()%5)); for(int i = 0; i < 10; i++) { printf("thread: %lu\\t counter = %d\\n", pthread_self(), i); sleep(rand()%2); } return 0; } extern pthread_mutex_t mutex; static int counter; void *countTo10000(void *data) { sleep(2); assert(data == 0); while(1) { pthread_mutex_lock(&mutex); if(counter == 10000) break; counter++; pthread_mutex_unlock(&mutex); sleep(1); } printf("counter = %d\\n", counter); pthread_mutex_unlock(&mutex); return 0; }
1
#include <pthread.h> { int _data; struct listnode* _next; }Node,*Node_p,**Node_pp; Node_p _h = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int IsEmpty(Node_p _h) { return (_h->_next == 0)?1:0; } Node_p BuyNode(int data) { Node_p newnode = (Node_p)malloc(sizeof(Node)); if(newnode) { newnode->_data = data; newnode->_next = 0; } return newnode; } void InitList(Node_pp _h) { *_h = BuyNode(0); } void PushFront(Node_p _h,int data) { assert(_h); Node_p _n = BuyNode(data); _n->_next = _h->_next; _h->_next = _n; } void PopFront(Node_p _h,int* outdata) { assert(_h); if(!IsEmpty(_h)) { Node_p del = _h->_next; _h->_next = del->_next; *outdata = del->_data; free(del); } } void DistroyNode(Node_p _h) { assert(_h); int data = 0; while(!IsEmpty(_h)) { PopFront(_h,&data); } free(_h); _h = 0; } void Print(Node_p _h) { assert(_h); Node_p cur = _h->_next; while(cur) { printf("cur->_data->:%d",cur->_data); cur = cur->_next; } printf("\\n"); } void* product(void* arg) { int data = 0; while(1) { data = rand()%100; pthread_mutex_lock(&mutex); PushFront(_h,data); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); printf("productor:%d\\n",data); sleep(1); } return 0; } void* consume(void* arg) { int data = 0; while(1) { pthread_mutex_lock(&mutex); while(IsEmpty(_h)) { pthread_cond_wait(&cond,&mutex); } PopFront(_h,&data); pthread_mutex_unlock(&mutex); printf("consumer:%d\\n",data); sleep(1); } return 0; } void* thread(void* arg) { int data = 0; while(1) { pthread_mutex_lock(&mutex); while(IsEmpty(_h)) { pthread_cond_wait(&cond,&mutex); } PopFront(_h,&data); pthread_mutex_unlock(&mutex); printf("tid:%d\\n",data); sleep(2); } } int main() { InitList(&_h); pthread_t productor,consumer,tid; pthread_create(&productor,0,product,0); pthread_create(&consumer,0,consume,0); pthread_create(&tid,0,thread,0); pthread_join(productor,0); pthread_join(consumer,0); pthread_join(tid,0); DistroyNode(_h); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); }
0
#include <pthread.h> const int mul_a[7] = {2769, 4587, 8761, 9031, 6743, 7717, 9913}; const int add_b[7] = {767, 1657, 4057, 8111, 11149, 11027, 9901}; void *bloomThread(void *args) { struct sharedData* sd = (struct sharedData *)args; int tid = sd->threadid; struct Bloom* bloom = sd->b; int x, opt; int i; char filename[sizeof "file100.txt"]; sprintf(filename, "file%03d.txt", tid); FILE *fp = fopen(filename,"r"); fscanf(fp, "%d %d\\n",&opt, &x); struct hashData* hdata = (struct hashData*)malloc(sizeof(struct hashData)); hdata->bloom = sd->b; int arr[NUM_OF_HASH]; hdata->arr = arr; while (fscanf(fp, "%d %d\\n",&opt, &x) == 2) { pthread_t threads[NUM_OF_HASH]; for( i = 0 ; i < NUM_OF_HASH ; i++ ) { hdata->tid = i; hdata->x = x; int rc = pthread_create(&threads[i], 0, hashCalculate, (void *)hdata); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n in main", rc); exit(-1); } } for( i = 0 ; i < NUM_OF_HASH ; i++ ) { pthread_join(threads[i],0); } sortHashes(arr); if(opt){ insertHash(arr, bloom); } else { if(findHash(arr, bloom)) printf("%d may be present\\n",x); else continue; } } free(hdata); fclose(fp); free(sd); pthread_exit(0); } void sortHashes(int a[]){ int i,j, temp; for(i=0;i< NUM_OF_HASH;i++){ for(j=0;j<NUM_OF_HASH;j++){ if(a[i]<a[j]) { temp = a[i]; a[i] =a[j]; a[j] = temp; } } } } void* hashCalculate(void* hdata){ struct hashData* hd = (struct hashData*)hdata; int id = hd->tid; hd->arr[id] = (mul_a[id]*hd->x + add_b[id])%19997; if(hd->arr[id] < 0) hd->arr[id]*=-1; pthread_exit(0); } void getLocks(int a[], struct Bloom* b){ int i,j; for(i =1; i<NUM_OF_HASH;i++){ if(a[i] == a[i-1]); continue; pthread_mutex_lock(&(b->mutexArr[a[i]])); } } void releaseLocks(int a[], struct Bloom* b){ int i,j; for(i =0; i<NUM_OF_HASH;i++){ if(a[i] == a[i-1]); continue; pthread_mutex_unlock(&(b->mutexArr[a[i]])); } } void insertHash(int a[], struct Bloom* b){ int i; getLocks(a,b); for(i =0; i<NUM_OF_HASH;i++){ if(b->bit[a[i]] == 1) continue; else b->bit[a[i]] = 1; } releaseLocks(a,b); } int findHash(int a[], struct Bloom* b){ getLocks(a,b); int i,j =1; for(i =0; i<NUM_OF_HASH;i++){ if(b->bit[a[i]] == 1) continue; else j= 0; } releaseLocks(a,b); return j; }
1
#include <pthread.h> pthread_t thread[6]; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; double result; { int n; } calc_data; int isOdd(int n) { if(n%2) return 1; else return -1; } void* nilakantha_series(void* arg) { calc_data *c_data = (calc_data*) arg; int n = c_data->n; double approx; if(n + 1 == 1) { approx = 3; } else if(n + 1 == 2) { approx = (4 / (double) ((2*n) * ((2*n)+1) * ((2*n)+2))); } else { approx = (4 / (double) ((2*n) * ((2*n)+1) * ((2*n)+2)) * isOdd(n)); } printf("in result for n=%d is %f\\n", n, approx); pthread_mutex_lock(&lock); result += approx; pthread_mutex_unlock(&lock); pthread_exit(0); } int main(void) { int t, rc; calc_data c_data; for(t=0; t<6; t++) { c_data.n = t; rc = pthread_create(&thread[t], 0, nilakantha_series, (void*) &c_data); usleep(1000); if(rc) { printf("error in thread create with status %d\\n", rc); return -1; } } printf("\\n"); for(t=0; t<6; t++) { pthread_join(thread[t], 0); } pthread_mutex_destroy(&lock); printf("\\npi approximation: %f\\n", result); return 0; }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void* funcCnt1(); void* funcCnt2(); int count = 0; int main() { pthread_t thread1, thread2; pthread_create(&thread1, 0, funcCnt1, 0); pthread_create(&thread2, 0, funcCnt2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); printf("Final count: %d\\n", count); exit(0); } void* funcCnt1() { while (1) { pthread_mutex_lock(&count_mutex); printf("fun1 waiting\\n"); pthread_cond_wait(&condition_var, &count_mutex); count++; printf("Counter value funcCnt1: %d\\n", count); pthread_mutex_unlock(&count_mutex); if(count >= 10) return 0; } } void* funcCnt2() { while (1) { pthread_mutex_lock(&count_mutex); if (count < 3 || count > 6) { printf("fun2 sent signal to fun1\\n"); pthread_cond_signal(&condition_var); } else { count++; printf("Counter value funcCnt2: %d\\n", count); } pthread_mutex_unlock(&count_mutex); if (count >= 10) return 0; } }
1
#include <pthread.h> int buffer[10]; int imprimir=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condProd=PTHREAD_COND_INITIALIZER; pthread_cond_t condCons=PTHREAD_COND_INITIALIZER; void *codigo_productor(void *_id); void *codigo_consumidor(void *_id); void imprimir_vector(); void producir(int); void consumir(int); int main(){ int i; pthread_t hilo_productor[5]; pthread_t hilo_consumidor[5]; int idp[5]; int idc[5]; int error; int *salida; for(i=0;i<5;i++){ idp[i]=i; idc[i]=i+10; } for(i=0;i<5;i++){ error = pthread_create(&hilo_productor[i],0,codigo_productor,&idp[i]); if(error){ fprintf(stderr,"Error %d: %s\\n",error, strerror(error)); exit(-1); } } for(i=0;i<5;i++){ error = pthread_create(&hilo_consumidor[i],0,codigo_consumidor,&idc[i]); if(error){ fprintf(stderr,"Error %d: %s\\n",error, strerror(error)); exit(-1); } } error = pthread_join(hilo_productor[1],(void **)&salida); if(error) fprintf(stderr,"Error %d: %s\\n",error,strerror(error)); else{ printf("Hilo %d terminado,%d\\n",*salida,idp[1-1]); } return 0; } void imprimir_vector(){ int i; printf("\\n"); for(i=0;i<imprimir;i++){printf("%d->",buffer[i]);} printf("\\n\\n"); } void *codigo_productor(void *_id){ int id = *(int *)_id; usleep(1000-100*id); while(1){ pthread_mutex_lock(&mutex); while(imprimir==10){pthread_cond_wait(&condProd,&mutex);} producir(id); pthread_cond_signal(&condCons); pthread_mutex_unlock(&mutex); } pthread_exit(&id); } void *codigo_consumidor(void *_id){ int id = *(int *)_id; usleep(1000-100*id); while(1){ pthread_mutex_lock(&mutex); while(imprimir==0){pthread_cond_wait(&condCons,&mutex);} consumir(id); pthread_cond_signal(&condProd); pthread_mutex_unlock(&mutex); } pthread_exit(&id); } void producir(int id){ printf("Productor con id: %d\\n",id); buffer[imprimir]=id; imprimir++; imprimir_vector(); } void consumir(int id){ printf("Consumidor con id %d\\n consumio: %d",id,buffer[imprimir]); buffer[imprimir]=0; imprimir--; imprimir_vector(); }
0
#include <pthread.h> void* irTimeoutFunction(void* args){ struct ArgumentData *ad = (struct ArgumentData *)args; struct ElevatorData *ed = ad->ed; pthread_mutex_t *mutex = ad->mutex; while(1){ long theTime = time(0); pthread_mutex_lock(mutex); if(ed->doorOpenFlag){ if(theTime - ed->lastIRTime > INITIAL_DOOR_WAIT_TIME && ed->initialDoorWaitOverFlag == 1){ ed->initialDoorWaitOverFlag = 0; } if(theTime - ed->lastIRTime > IR_DOOR_WAIT_TIME && ed->initialDoorWaitOverFlag == 0){ logString("Closing Door", LOG_LEVEL_DEBUG); ed->doorFlag = 0; closeDoor(ed); } } pthread_mutex_unlock(mutex); } } void irTriggerFunction(struct ElevatorData *ed, pthread_mutex_t *mutex){ pthread_mutex_lock(mutex); if(ed->doorOpenFlag){ long theTime = time(0); ed->lastIRTime = theTime; ed->doorFlag = 1; } pthread_mutex_unlock(mutex); } void* irInterruptFunction(void* args){ struct ArgumentData *ad = (struct ArgumentData *)args; struct ElevatorData *ed = ad->ed; pthread_mutex_t *mutex = ad->mutex; while(1){ if(0){ irTriggerFunction(ed, mutex); } } } void* reachFloorInterruptFunction(void* args){ struct ArgumentData *ad = (struct ArgumentData *)args; struct ElevatorData *ed = ad->ed; pthread_mutex_t *mutex = ad->mutex; int checkForElevatorFloorReach = 0; while(1){ if(checkForElevatorFloorReach){ reachFloorTriggerFunction(ed, mutex); } } } void reachFloorTriggerFunction(struct ElevatorData *ed, pthread_mutex_t *mutex){ pthread_mutex_lock(mutex); ed->reachedFloorFlag = 1; pthread_mutex_unlock(mutex); } void* keyInterruptFunction(void* args){ struct ArgumentData *ad = (struct ArgumentData *)args; struct ElevatorData *ed = ad->ed; pthread_mutex_t *mutex = ad->mutex; char str[50]; str[0] = 'n'; while(1){ fgets(str, 50, stdin); printf("%s\\n", str); if(str[0] == FLOOR_CHAR_INTERNAL_ONE){ floorQueueManager(ed, mutex, FLOOR_ONE_REQUEST); } else if(str[0] == FLOOR_CHAR_INTERNAL_TWO){ floorQueueManager(ed, mutex, FLOOR_TWO_REQUEST); } else if(str[0] == FLOOR_CHAR_INTERNAL_THREE){ floorQueueManager(ed, mutex, FLOOR_THREE_REQUEST); } else if(str[0] == FLOOR_CHAR_EXTERNAL_ONE_UP){ if(elevatorIsOnFloor(ed, mutex, 1)){ pthread_mutex_lock(mutex); openDoorRoutine(ed); pthread_mutex_unlock(mutex); } else{ floorQueueManager(ed, mutex, FLOOR_ONE_UP_REQUEST); } } else if(str[0] == FLOOR_CHAR_EXTERNAL_TWO_UP){ if(elevatorIsOnFloor(ed, mutex, 2)){ pthread_mutex_lock(mutex); openDoorRoutine(ed); pthread_mutex_unlock(mutex); } else{ floorQueueManager(ed, mutex, FLOOR_TWO_UP_REQUEST); } } else if(str[0] == FLOOR_CHAR_EXTERNAL_TWO_DOWN){ if(elevatorIsOnFloor(ed, mutex, 2)){ pthread_mutex_lock(mutex); openDoorRoutine(ed); pthread_mutex_unlock(mutex); } else{ floorQueueManager(ed, mutex, FLOOR_TWO_DOWN_REQUEST); } } else if(str[0] == FLOOR_CHAR_EXTERNAL_THREE_DOWN){ if(elevatorIsOnFloor(ed, mutex, 3)){ pthread_mutex_lock(mutex); openDoorRoutine(ed); pthread_mutex_unlock(mutex); } else{ floorQueueManager(ed, mutex, FLOOR_THREE_DOWN_REQUEST); } } else if(str[0] == 'y'){ printf("%s\\n", "Triggering IR Interrupt"); irTriggerFunction(ed, mutex); } else if(str[0] == 'h'){ printf("%s\\n", "Triggering ReachFloor Interrupt"); reachFloorTriggerFunction(ed, mutex); } else if(str[0] == 'n'){ pthread_mutex_lock(mutex); debugBlock(ed); pthread_mutex_unlock(mutex); } } } int elevatorIsOnFloor(struct ElevatorData *ed, pthread_mutex_t *mutex, int reqFloorNum){ pthread_mutex_lock(mutex); if(ed->currentFloor == reqFloorNum && ed->nextFloor == ed->currentFloor){ pthread_mutex_unlock(mutex); return 1; } else{ pthread_mutex_unlock(mutex); return 0; } pthread_mutex_unlock(mutex); }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
0
#include <pthread.h> static pthread_once_t g_init = PTHREAD_ONCE_INIT; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static struct light_state_t g_battery; char const*const CHARGING_LED_FILE = "/sys/class/leds/charging/brightness"; char const*const LCD_FILE = "/sys/class/leds/lcd-backlight/brightness"; void init_globals(void) { pthread_mutex_init(&g_lock, 0); } static int write_int(char const* path, int value) { int fd; static int already_warned = 0; fd = open(path, O_RDWR); if (fd >= 0) { char buffer[20]; int bytes = sprintf(buffer, "%d\\n", value); int amt = write(fd, buffer, bytes); close(fd); return amt == -1 ? -errno : 0; } else { if (already_warned == 0) { ALOGE("write_int failed to open %s\\n", path); already_warned = 1; } return -errno; } } static int is_lit(struct light_state_t const* state) { return state->color & 0x00ffffff; } static int rgb_to_brightness(struct light_state_t const* state) { int color = state->color & 0x00ffffff; return ((77*((color>>16)&0x00ff)) + (150*((color>>8)&0x00ff)) + (29*(color&0x00ff))) >> 8; } static int set_light_backlight( struct light_device_t* dev, struct light_state_t const* state) { int err = 0; int brightness = rgb_to_brightness(state); pthread_mutex_lock(&g_lock); err = write_int(LCD_FILE, brightness); pthread_mutex_unlock(&g_lock); return err; } static int set_speaker_light_locked(struct light_state_t const* state) { int brightness_level; if (is_lit(state)) brightness_level = 255; else brightness_level = 0; return write_int(CHARGING_LED_FILE, 0); } static int handle_speaker_battery_locked() { return set_speaker_light_locked(&g_battery); } static int set_light_battery( struct light_device_t* dev, struct light_state_t const* state) { int err = 0; pthread_mutex_lock(&g_lock); g_battery = *state; err = handle_speaker_battery_locked(); pthread_mutex_unlock(&g_lock); return err; } static int close_lights(struct light_device_t *dev) { if (dev) { free(dev); } return 0; } static int open_lights(const struct hw_module_t* module, char const* name, struct hw_device_t** device) { int (*set_light)(struct light_device_t* dev, struct light_state_t const* state); if (0 == strcmp(LIGHT_ID_BACKLIGHT, name)) set_light = set_light_backlight; else if (0 == strcmp(LIGHT_ID_BATTERY, name)) set_light = set_light_battery; else return -EINVAL; pthread_once(&g_init, init_globals); struct light_device_t *dev = malloc(sizeof(struct light_device_t)); memset(dev, 0, sizeof(*dev)); dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 0; dev->common.module = (struct hw_module_t*)module; dev->common.close = (int (*)(struct hw_device_t*))close_lights; dev->set_light = set_light; *device = (struct hw_device_t*)dev; return 0; } static struct hw_module_methods_t lights_module_methods = { .open = open_lights, }; struct hw_module_t HAL_MODULE_INFO_SYM = { .tag = HARDWARE_MODULE_TAG, .version_major = 1, .version_minor = 0, .id = LIGHTS_HARDWARE_MODULE_ID, .name = "MSM8916 lights Module", .author = "Google, Inc., dhacker29", .methods = &lights_module_methods, };
1
#include <pthread.h> void *addr; int cnt; char code; } ac_ent; static ac_ent ac_tlb[10] = {{0,0,0},}; static pthread_mutex_t mutex; static void __init(void){ pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_FAST_NP); pthread_mutex_init(&mutex, &attr); memset(ac_tlb, 0, sizeof(ac_tlb)); } int ac_tlb_insert(void *addr, char code){ int i; ac_ent *e, *inserted=0; pthread_mutex_lock(&mutex); for(i=0; i<10 && ac_tlb[i].addr != 0; i++){ e = &ac_tlb[i]; if(e->addr == addr){ assert(e->code == code); e->cnt++; pthread_mutex_unlock(&mutex); return i; } else if( inserted == 0 && e->cnt == 0 ){ inserted = e; } } if( inserted == 0 && i<10 ){ inserted = &ac_tlb[i]; } if(inserted){ inserted->addr = addr; inserted->cnt = 1; inserted->code = code; pthread_mutex_unlock(&mutex); return (inserted - ac_tlb); } else { abort(); } } char ac_tlb_remove(void *addr, int *cnt){ int i; ac_ent *e; pthread_mutex_lock(&mutex); for(i=0; i<10 && ac_tlb[i].addr != 0; i++){ e = &ac_tlb[i]; if(e->addr == addr){ *cnt = --(e->cnt); pthread_mutex_unlock(&mutex); return e->code; } } abort(); }
0
#include <pthread.h> double sum = 0.0, a[1000000]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, start, *mytid, end; double mysum = 0.0; mytid = (int *) tid; start = (*mytid * 1000000/4); end = start + 1000000/4; printf("Thread %d doing iterations %d to %d\\n", *mytid, start, end - 1); for (i = start; i < end; i++) { a[i] = i * 1.0; mysum += a[i]; } pthread_mutex_lock(&sum_mutex); sum += mysum; pthread_mutex_unlock(&sum_mutex); pthread_exit(0); } int main(int argc, char **argv) { int i, tids[4]; pthread_t threads[4]; pthread_attr_t attr; pthread_mutex_init(&sum_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 4; i++) { tids[i] = i; pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]); } for (i = 0; i < 4; i++) { pthread_join(threads[i], 0); } printf("Done. Sum = %e\\n", sum); sum = 0.0; for (i = 0; i < 1000000; i++) { a[i] = i * 1.0; sum = sum + a[i]; } printf("Check sum = %e\\n", sum); pthread_attr_destroy(&attr); pthread_mutex_destroy(&sum_mutex); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bufferFullStatus = PTHREAD_COND_INITIALIZER; pthread_cond_t bufferEmptyStatus = PTHREAD_COND_INITIALIZER; int numConsumers; int totalWorkUnits; struct workUnit { char* data; }; struct workQueue { int size; int maxSize; struct workUnit** workUnits; }; struct workUnit* newWorkUnit(char* st) { struct workUnit* newWU = malloc(sizeof(struct workUnit)); newWU->data = st; return newWU; } struct workQueue* newWorkQueue(int maxSize) { struct workQueue* newWQ = malloc(sizeof(struct workQueue)); newWQ->size = 0; newWQ->maxSize = maxSize; newWQ->workUnits = malloc(sizeof(struct workUnit*) * maxSize); return newWQ; } void timer(int length) { int i = length; while(i > 0) { i--; } return; } void* produce(void* passedWQptr) { struct workQueue* wQ = (struct workQueue*)passedWQptr; int numProduced = 0; int numToProduce = totalWorkUnits; while(numProduced < numToProduce) { char* data = "Peter_Meehan_2015"; timer(10000000); pthread_mutex_lock(&mutex); { system("clear"); int size = wQ->size; printf("\\n\\n\\n\\tWork Queue Build Up:\\n\\t"); int i; for(i = 0; i < 50; i++) { if(i!=0 && i%10 == 0) { printf("\\x1b[0m" "\\n\\t"); } if(i < size) { printf("\\x1b[31m" "[%.2i] ", i); } else { printf("\\x1b[32m" "[ ] "); } } printf("\\x1b[0m" "\\n"); }; printf("numProduced = %i\\n", numProduced); if(wQ->size < wQ->maxSize) { wQ->workUnits[wQ->size] = newWorkUnit(data); wQ->size++; numProduced++; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&bufferEmptyStatus); } else { pthread_mutex_unlock(&mutex); pthread_cond_wait(&bufferFullStatus, &mutex); } } return 0; } void* consume(void* passedWQptr) { struct workQueue* wQ = (struct workQueue*)passedWQptr; int numConsumed = 0; int numToConsume = totalWorkUnits/numConsumers; while(numConsumed < numToConsume) { pthread_mutex_lock(&mutex); if(wQ->size > 0) { wQ->size--; { system("clear"); int size = wQ->size; printf("\\n\\n\\n\\tWork Queue Build Up:\\n\\t"); int i; for(i = 0; i < 50; i++) { if(i!=0 && i%10 == 0) { printf("\\x1b[0m" "\\n\\t"); } if(i < size) { printf("\\x1b[31m" "[%.2i] ", i); } else { printf("\\x1b[32m" "[ ] "); } } printf("\\x1b[0m" "\\n"); }; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&bufferFullStatus); numConsumed++; timer(40000000); } else { pthread_mutex_unlock(&mutex); pthread_cond_wait(&bufferEmptyStatus, &mutex); } pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char* argv[]) { if(argc != 2) { fprintf(stderr, "Useage:\\t./sexy_pc <number of consumers>\\n"); exit(1); } numConsumers = atoi(argv[1]); if(numConsumers < 1 || numConsumers > 2048) { fprintf(stderr, "That amount of consumers isn't sensible. Take care.\\n"); exit(1); } totalWorkUnits = numConsumers * 100; if(totalWorkUnits<100) { fprintf(stderr, "Something went wrong calculating how many work units to make. Please contact your system administrator.\\n"); exit(1); } fprintf(stderr, "Starting process:\\nNumber of Consumers = %i\\nTotal Work Units = %i\\nUnits Per Consumer = %i\\n\\n", numConsumers, totalWorkUnits, 100); struct workQueue* workQ = newWorkQueue(50); pthread_t producer; if(pthread_create(&producer, 0, produce, workQ)) { fprintf(stderr, "Error creating producer\\n"); return 1; } pthread_cond_signal(&bufferFullStatus); pthread_t consumers[numConsumers]; int i; for(i = 0; i < numConsumers; i++) { if(pthread_create(&consumers[i], 0, consume, workQ)) { return 1; } } fprintf(stderr, "\\n" ); if(pthread_join(producer, 0)) { return 2; } fprintf(stderr, "Producer joined main thread successfully!\\n"); for(i = 0; i < numConsumers; i++) { if(pthread_join(consumers[i], 0)) { return 2; } } return 0; }
0