text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int is_exiting = 0; buffer_item buffer[5]; int buffer_space = 5; pthread_mutex_t buffer_lock; int buffer_has_space(); int buffer_has_item(); int insert_item(buffer_item item); int remove_item(buffer_item *item); void *producer(void *param); void *consumer(void *param); int buffer_has_space() { return buffer_space > 0; } int buffer_has_item() { return buffer_space < 5; } int insert_item(buffer_item item) { int is_inserted_item = 0, buf_pos; while (!is_inserted_item && !is_exiting) { pthread_mutex_lock(&buffer_lock); if (buffer_has_space()) { buf_pos = 5 - buffer_space; buffer[buf_pos] = item; buffer_space--; is_inserted_item = 1; } pthread_mutex_unlock(&buffer_lock); } return is_inserted_item ? 0 : -1; } int remove_item(buffer_item *item) { int i, is_removed_item = 0, buf_pos; while (!is_removed_item && !is_exiting) { pthread_mutex_lock(&buffer_lock); if (buffer_has_item()) { buf_pos = 5 - buffer_space - 1; *item = buffer[0]; buffer_space++; for (i = 0; i < buf_pos; i++) { buffer[i] = buffer[i + 1]; } is_removed_item = 1; } pthread_mutex_unlock(&buffer_lock); } return is_removed_item ? 0 : -1; } int main(int argc, char *argv[]) { int i, exec_duration, n_producer_threads, n_consumer_threads; pthread_t *producer_threads, *consumer_threads; if (argc < 4) { fprintf(stderr, "Not enough arguments\\n"); return 1; } else { exec_duration = atoi(argv[1]); n_producer_threads = atoi(argv[2]); n_consumer_threads = atoi(argv[3]); } for (i = 0; i < 5; i++) { buffer[i] = 0; } if (pthread_mutex_init(&buffer_lock, 0) != 0) { perror("pthread_mutex_init"); return 1; } producer_threads = (pthread_t*)malloc(sizeof(pthread_t) * n_producer_threads); if (producer_threads == 0) { perror("malloc"); return 1; } for (i = 0; i < n_producer_threads; i++) { if (pthread_create(&producer_threads[i], 0, producer, 0) != 0) { perror("pthread_create"); return 1; } } consumer_threads = (pthread_t*)malloc(sizeof(pthread_t) * n_consumer_threads); if (consumer_threads == 0) { perror("malloc"); return 1; } for (i = 0; i < n_consumer_threads; i++) { if (pthread_create(&consumer_threads[i], 0, consumer, 0) != 0) { perror("pthread_create"); return 1; } } sleep(exec_duration); is_exiting = 1; for (i = 0; i < n_producer_threads; i++) { if (pthread_join(producer_threads[i], 0) != 0) { perror("pthread_join"); return 1; } } for (i = 0; i < n_consumer_threads; i++) { if (pthread_join(consumer_threads[i], 0) != 0) { perror("pthread_join"); return 1; } } pthread_exit(0); if (pthread_mutex_destroy(&buffer_lock) != 0) { perror("pthread_mutex_destroy"); return 1; } return 0; } void *producer(void *param) { buffer_item item; while (1) { sleep(rand() % 3 + 1); item = rand(); if (insert_item(item) == -1) { if (is_exiting == 1) { fprintf( stderr, "Producer thread with thread id %ld exiting\\n", pthread_self() ); return 0; } else { fprintf(stderr,"Buffer is full\\n"); } } else { printf("Producer produced %d\\n",item); } } } void *consumer(void *param) { buffer_item item; while (1) { sleep(rand() % 3 + 1); if (remove_item(&item) == -1) { if (is_exiting == 1) { fprintf( stderr, "Consumer thread with thread id %ld exiting\\n", pthread_self() ); return 0; } else { fprintf(stderr,"Buffer is empty\\n"); } } else { printf("Consumer consumed %d\\n",item); } } }
1
#include <pthread.h> void *runner(void *param); int count = 0; pthread_mutex_t lock; int main(int argc, char **argv) { pthread_t tid1, tid2; int value; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); exit(1); } if(pthread_create(&tid1, 0, runner, 0)) { printf("\\n Error creating thread 1"); exit(1); } if(pthread_create(&tid2, 0, runner, 0)) { printf("\\n Error creating thread 2"); exit(1); } if(pthread_join(tid1, 0)) { printf("\\n Error joining thread"); exit(1); } if(pthread_join(tid2, 0)) { printf("\\n Error joining thread"); exit(1); } if (count < 2 * 1000000) printf("\\n ** ERROR ** count is [%d], should be %d\\n", count, 2*1000000); else printf("\\n OK! count is [%d]\\n", count); pthread_exit(0); pthread_mutex_destroy(&lock); return 0; } void *runner(void *param) { pthread_mutex_lock(&lock); int i, temp; for(i = 0; i < 1000000; i++) { temp = count; temp = temp + 1; count = temp; } pthread_mutex_unlock(&lock); }
0
#include <pthread.h> void wait_for_completion(struct completion *x) { pthread_mutex_lock(&x->lock); while(!x->done) { pthread_cond_wait(&x->cond, &x->lock); } x->done--; pthread_mutex_unlock(&x->lock); } unsigned long wait_for_completion_timeout(struct completion *x, unsigned long ms) { int ret; struct timeval now; struct timespec timeout; gettimeofday(&now, 0); timeout.tv_sec = now.tv_sec + ms / 1000; timeout.tv_nsec = now.tv_usec * 1000 + ((ms % 1000)*1000*1000); pthread_mutex_lock(&x->lock); ret = pthread_cond_timedwait(&x->cond, &x->lock, &timeout); if(ret == ETIMEDOUT) { logi("wait for completion timeout!\\n"); } else if(ret == 0) { x->done--; logi("receive the completion.\\n"); } else { ret = -1; loge("wait for completion error!\\n"); } pthread_mutex_unlock(&x->lock); return ret; } bool try_wait_for_completion(struct completion *x) { int ret = 1; pthread_mutex_lock(&x->lock); if (!x->done) ret = 0; else x->done--; pthread_mutex_unlock(&x->lock); return ret; } bool completion_done(struct completion *x) { int ret = 1; pthread_mutex_lock(&x->lock); if (!x->done) ret = 0; pthread_mutex_unlock(&x->lock); return ret; } void complete(struct completion *x) { pthread_mutex_lock(&x->lock); x->done++; pthread_cond_signal(&x->cond); pthread_mutex_unlock(&x->lock); } void complete_all(struct completion *x) { pthread_mutex_lock(&x->lock); x->done += 4294967295U/2; pthread_cond_broadcast(&x->cond); pthread_mutex_unlock(&x->lock); }
1
#include <pthread.h> void set_motor_par() { clear_to_color(screen, COL_BG); layout_base("Set motor parameters"); button_set(rectx1, recty1, "previus"); textout_centre_ex(screen, font, "SET THE PARAMETERS OF MOTOR", sezx/2, d, COL_BUT, BG); button_set(motparx1, motpary1-d/2, "Terminal Inductance (L)"); button_set(motparx1, motpary1+2*d, "Terminal Resistence (R)"); button_set(motparx1, motpary1+4.5*d, "Back-EMF constant (kb)"); button_set(motparx1, motpary1+7*d, "Torque Constant (kt)"); button_set(motparx1, motpary1+9.5*d, "Motor and Load Inercia (J)"); button_set(motparx1, motpary1+12*d, "Friction Constant (b)"); } void display_mot_par(int x, int y, struct select_motor *motor) { textout_ex(screen,font, "MOTOR PARAMETERS", x-r-d/2, y+r+2*d, COL_MOT_REF, BG); sprintf(p, "Terminal Inductance (L): %.3f", (*motor).L); textout_ex(screen,font, p, x-r-d/2, y+r+d+2*(d+h)/2, COL_MOT_REF, BG); sprintf(p, "Terminal Resistence (R): %.3f", (*motor).R); textout_ex(screen,font, p, x-r-d/2, y+r+d+3*(d+h)/2, COL_MOT_REF, BG); sprintf(p, "Back-EMF constant (kb): %.3f", (*motor).kb); textout_ex(screen,font, p, x-r-d/2, y+r+d+4*(d+h)/2, COL_MOT_REF, BG); sprintf(p, "Torque Constant (kt): %.3f", (*motor).kt); textout_ex(screen,font, p, x-r-d/2, y+r+d+5*(d+h)/2, COL_MOT_REF, BG); sprintf(p, "Motor and Load Inercia (J): %.3f", (*motor).J); textout_ex(screen,font, p, x-r-d/2, y+r+d+6*(d+h)/2, COL_MOT_REF, BG); sprintf(p, "Friction constant (b): %.3f", (*motor).b); textout_ex(screen,font, p, x-r-d/2, y+r+d+7*(d+h)/2, COL_MOT_REF, BG); } void mouse_task_set_motor_par(struct select_motor *motor, int sem) { if(click_button(motparx1,motpary1-d/2)) { textout_ex(screen, font, "Insert the value of terminal inductance (L): ", motparx1+d+2*l, motpary1-d/2-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1-d/2-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).L); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(motparx1, motpary1+2*d)) { textout_ex(screen, font, "Insert the value of terminal Resistence (R): ", motparx1+d+2*l, motpary1+2*d-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1+2*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).R); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(motparx1, motpary1+4.5*d)) { textout_ex(screen, font, "Insert the value of back-EMF (kb): ", motparx1+d+2*l, motpary1+4.5*d-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1+4.5*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).kb); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(motparx1, motpary1+7*d)) { textout_ex(screen, font, "Insert the value of torque constant (kt): ", motparx1+d+2*l, motpary1+7*d-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1+7*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).kt); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(motparx1, motpary1+9.5*d)) { textout_ex(screen, font, "Insert the value of motor and load Inercia (J): ", motparx1+d+2*l, motpary1+9.5*d-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1+9.5*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).J); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(motparx1, motpary1+12*d)) { textout_ex(screen, font, "Insert the value of friction constant (b): ", motparx1+d+2*l, motpary1+12*d-h/2, COL_MOT_REF, BG); get_string(p, motparx1+8*l, motpary1+12*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*motor).b); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(rectx1, recty1)) { pthread_mutex_lock(&mux_page); page = WORK_PAGE; but = 0; pthread_mutex_unlock(&mux_page); layout(); } }
0
#include <pthread.h> void receive(void *arg); void cleanup(int i); void add_login(char *name, char* host, int ppid); void del_login(char *name, char* host, int ppid); void get_logins(int sock); void parse (char *command, char *argv[], int *argc); struct heybook hey; pthread_mutex_t mutex; int main(int argc, char *argv[]) { pthread_t tid; int srv_sock = sockcreate(PORT); if (srv_sock == -1) { printf("Couldn't create socket.\\n"); exit(1); } pthread_mutex_init(&mutex, 0); printf("Hey-Server activating on port %ld.\\n", PORT); signal(SIGINT, cleanup); while (1) { int cl_sock = sockaccept(srv_sock); printf("Connection request received.\\n"); pthread_create(&tid, 0, (void*) &receive, (void*) cl_sock); } cleanup(0); return 0; } void cleanup(int i) { pthread_mutex_destroy(&mutex); exit(0); } void receive(void *arg) { int done = 0; int cl_sock = (int) arg; char buffer[MAX_BUFFER]; int argc; char *argv[5]; int i; while (!done) { recv (cl_sock, buffer, sizeof(buffer), 0); i = 0; while (buffer[i++]!=';') {} buffer[i]='\\0'; printf("Received message: '%s'\\n", buffer); parse (buffer, argv, &argc); if ( !strcmp(argv[0], "LOGIN") ) { if (argc < 4) printf("Wrong number of arguments (%d).\\n",argc); else add_login (argv[1], argv[2], (int)(atoi(argv[3]))); } else if ( !strcmp(argv[0], "LOGOUT") ) { if (argc < 4) { printf("Wrong number of arguments (%d).\\n",argc); close(cl_sock); printf("Thread exiting with error.\\n"); pthread_exit(0); } else { del_login (argv[1], argv[2], (int)(atoi(argv[3]))); done = 1; } } else if ( !strcmp(argv[0], "HEY") ) { if (argc < 1) printf("Wrong number of arguments (%d).\\n",argc); else get_logins(cl_sock); } else { printf("Unrecognized command.\\n"); } } close(cl_sock); printf("Thread exiting.\\n"); pthread_exit(0); } void add_login(char *name, char* host, int ppid) { int index = -1; printf("Adding: name = %s, host = %s, pid = %d.\\n", name, host, ppid); pthread_mutex_lock(&mutex); index = hey.count++; strcpy(hey.login[index].name, name); strcpy(hey.login[index].host, host); hey.login[index].ppid = (int) (ppid); pthread_mutex_unlock(&mutex); } void del_login (char *name, char* host, int ppid) { int i; int index = -1; printf("Deleting: name = %s, host = %s, pid = %d.\\n", name, host, ppid); pthread_mutex_lock(&mutex); for (i = 0; i < hey.count; i++) if (hey.login[i].ppid == ppid && !strcmp(hey.login[i].name, name) ) { index = i; break; } if (index != -1) { int last = --hey.count; if (index != last) { strcpy(hey.login[index].name, hey.login[last].name); strcpy(hey.login[index].host, hey.login[last].host); hey.login[index].ppid = hey.login[last].ppid; } } else { printf("\\n\\n ERROR IN HEYBOOK !!! \\n\\n"); } pthread_mutex_unlock(&mutex); } void get_logins(int sock) { int i; printf("Sending HeyBook...\\n"); pthread_mutex_lock(&mutex); for (i = 0; i < hey.count; i++) { char buffer[MAX_BUFFER]; sprintf (buffer, "%s,%s,%d;", hey.login[i].name, hey.login[i].host, hey.login[i].ppid); } send(sock, (char *) &hey, sizeof(struct heybook), 0); pthread_mutex_unlock(&mutex); } void parse (char *command, char *argv[], int *argc) { int i=0; char *ptr, *next; argv[i++] = strtok_r (command, ",;", &next); while ( (ptr = strtok_r (0, ",;", &next)) ) { argv [i++] = ptr; } *argc = i; argv[i] = 0; }
1
#include <pthread.h> pthread_t threads[4]; pthread_mutex_t mutex; unsigned int * V; int divisor = 2; double limit; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void * criba(void * tid){ int mydiv=0; int j; while (mydiv < limit){ pthread_mutex_lock(&mutex); mydiv = divisor; divisor++; pthread_mutex_unlock(&mutex); for (j = 0; j < 2097152; j++){ if (V[j] != 0){ if ((V[j] % mydiv) == 0){ V[j] = 0; } } } } printf("Thread %ld terminado, mydiv = %d\\n", tid, mydiv); pthread_exit(0); } int main (int argc, char ** argv){ double timetick; int i,j; limit = sqrt(2097152) + 1; timetick = dwalltime(); if (0 == (V = malloc(2097152 * sizeof(unsigned int)))){ printf("No hay memoria suficiente :(\\n"); return -1; } for (i = 0; i < 2097152 - 1; i++){V[i] = i;} printf("Inicialización = %f\\n", dwalltime() - timetick); pthread_mutex_lock(&mutex); for (i = 0; i < 4; i++){ pthread_create( &threads[i], 0, criba, (void*)i); } pthread_mutex_unlock(&mutex); timetick = dwalltime(); for (i = 0; i < 4; i++){ pthread_join( threads[i], 0); } printf("Criba completa = %f\\n", dwalltime() - timetick); for (i = 0; i < 2097152; i++){ if (V[i] != 0){ } } return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex_ressources = PTHREAD_MUTEX_INITIALIZER; static unsigned int nb_ressources = 4; static pthread_cond_t cond_ressources_libere = PTHREAD_COND_INITIALIZER; void f_thread(unsigned int *ressources_necessaires) { pthread_t current_thread = pthread_self(); pthread_mutex_lock(&mutex_ressources); while (nb_ressources < *ressources_necessaires) { printf("*** Thread[%lu] ***\\nJe veux %u ressources", current_thread, *ressources_necessaires); printf(" mais il y a %u ressources\\n\\n", nb_ressources); pthread_cond_wait(&cond_ressources_libere, &mutex_ressources); } printf("*** Thread[%lu] ***\\nJe prends %u ressources", current_thread, *ressources_necessaires); nb_ressources -= *ressources_necessaires; printf(" donc il reste %u ressources\\n\\n", nb_ressources); pthread_mutex_unlock(&mutex_ressources); sleep(3); pthread_mutex_lock(&mutex_ressources); printf("*** Thread[%lu] ***\\nJe libère %u ressources", current_thread, *ressources_necessaires); nb_ressources += *ressources_necessaires; printf(" donc il reste %u ressources\\n\\n", nb_ressources); pthread_cond_broadcast(&cond_ressources_libere); pthread_mutex_unlock(&mutex_ressources); } int main(int argc, char** argcv) { pthread_t thread1, thread2, thread3; unsigned int r1 = 3, r2 = 2, r3 = 1; pthread_create(&thread1, 0, (fct_ptr_t)f_thread, &r1); pthread_create(&thread2, 0, (fct_ptr_t)f_thread, &r2); pthread_create(&thread3, 0, (fct_ptr_t)f_thread, &r3); pthread_exit(0); return 0; }
1
#include <pthread.h> void * ucr (void * arg); void * uad (void * arg); void muestreoPeriodico (int ids); void escribirEnArchivo (int noAEscribir,int unidad, int tipo); void fueraDeRango (int ads); void apagarSistema (int ids); int encendido = 1; int * valores; int * valoresFueraDeRango; int * cambioEnValor; pthread_t * uads; pthread_t ucrTID; pthread_mutex_t mutexCambio = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t * mutexValores; FILE *f; int main(int argc, char const *argv[]) { signal(SIGINT,apagarSistema); srand((int)time(0)); f = fopen("reporte.txt", "w+"); if (f == 0) { printf("Error opening file!\\n"); exit(1); } valores = (int *)malloc(5*sizeof(int)); valoresFueraDeRango = (int *)malloc(5*sizeof(int)); cambioEnValor = (int *)malloc(5*sizeof(int)); int * auxCambio = cambioEnValor; int * finCambio = cambioEnValor + 5; for (;auxCambio < finCambio; ++auxCambio){ *auxCambio = 0; } mutexValores = (pthread_mutex_t *)malloc(5*sizeof(pthread_mutex_t)); pthread_mutex_t * auxValores = mutexValores; pthread_mutex_t * finValores = mutexValores + 5; for (;auxValores<finValores;++auxValores){ pthread_mutex_init(auxValores,0); } pthread_create(&ucrTID,0,ucr,0); uads = (pthread_t *)malloc(5*sizeof(pthread_t)); pthread_t * uadsAux = uads; pthread_t * fin = uads + 5; for (;uadsAux < fin; ++uadsAux){ pthread_create(uadsAux, 0, uad, (void *)(5 - (fin-uadsAux))); } pthread_exit(0); free(valores); free(valoresFueraDeRango); free(cambioEnValor); free(uads); free(mutexValores); fclose(f); return 0; } void apagarSistema (int ids){ printf("Apagando el sistema ...\\n"); encendido = 0; } void fueraDeRango (int ads){ pthread_mutex_lock(&mutexCambio); int * auxCambio = cambioEnValor; int * finCambio = cambioEnValor + 5; int valorFueraDeRango; int uadId; for (;auxCambio < finCambio; ++auxCambio){ if (*auxCambio){ uadId = (5 - (finCambio-auxCambio)); valorFueraDeRango = *(valoresFueraDeRango + uadId); printf("Soy la unidad central, la UAD %d tuvo el valor %d que es fuera de rango!\\n", uadId,valorFueraDeRango); *auxCambio = 0; } } pthread_mutex_unlock(&mutexCambio); escribirEnArchivo(valorFueraDeRango,uadId,0); } void * ucr (void * arg){ alarm(15); signal(SIGUSR1,fueraDeRango); signal(SIGALRM, muestreoPeriodico); while (encendido); pthread_exit(0); } void muestreoPeriodico (int ids) { alarm(15); int * auxValores = valores; int * finValores = valores + 5; int uadId; printf("Toca un muestreo periodico, se escribirá en el archivo\\n"); for (;auxValores < finValores;++auxValores) { uadId = (5 - (finValores - auxValores)); pthread_mutex_lock(mutexValores + uadId); escribirEnArchivo(*auxValores,uadId,1); pthread_mutex_unlock(mutexValores + uadId); } } void escribirEnArchivo (int noAEscribir,int unidad, int tipo){ if (tipo){ fprintf(f,"Lectura: %d (unidad %d) \\n",noAEscribir,unidad); }else { fprintf(f,"Lectura fuera de rango: %d (unidad %d) \\n",noAEscribir,unidad); } } void * uad (void * arg){ int uadId = (int) arg; int valorActual; printf("Soy el UAD con id %d \\n", uadId); while (encendido){ pthread_mutex_lock(mutexValores + uadId); *(valores + uadId) = valorActual = (rand() % 15) + 1; pthread_mutex_unlock(mutexValores + uadId); if (valorActual > 13){ printf("Soy la unidad %d y tuve un registro fuera de zona\\n", uadId); *(valoresFueraDeRango + uadId) = valorActual; pthread_mutex_lock(&mutexCambio); *(cambioEnValor + uadId) = 1; pthread_kill(ucrTID, SIGUSR1); pthread_mutex_unlock(&mutexCambio); } sleep(2); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t barber_access; pthread_mutex_t seat_access; int customer_access = 0; int num_free_seats = 5; bool shop_open = 1; void wait_for_customer() { while(customer_access <= 0) { ; } customer_access -= 1; } void customer_available() { customer_access += 1; } void* barber() { while(shop_open) { printf("[Barber]: waiting for customer\\n"); wait_for_customer(); pthread_mutex_lock(&seat_access); num_free_seats++; printf("[Barber]: calling customer over\\n"); pthread_mutex_unlock(&barber_access); pthread_mutex_unlock(&seat_access); printf("[Barber]: cutting hair\\n"); sleep(3); } return 0; } void* customer(void* rank) { pthread_mutex_lock(&seat_access); if(num_free_seats > 0) { num_free_seats--; printf("[%d]: found seat\\n", (int)rank); customer_available(); pthread_mutex_unlock(&seat_access); printf("[%d]: waiting for barber\\n", (int)rank); pthread_mutex_lock(&barber_access); printf("[%d]: leaving\\n", (int)rank); } else { pthread_mutex_unlock(&seat_access); printf("no seats available\\n"); } return 0; } int main(int argc, char* argv[]) { int num_customers = 10; if(argc == 2) num_customers = atoi(argv[1]); pthread_mutex_init(&barber_access, 0); pthread_mutex_init(&seat_access, 0); pthread_t* barber_handle; pthread_create((void*)&barber_handle, 0, barber, 0); pthread_mutex_lock(&barber_access); pthread_t* cust_handles = (pthread_t*) malloc(num_customers*sizeof(pthread_t*)); for(long thread=0; thread<num_customers; thread++) { sleep(rand() % 5); pthread_create((void*)&cust_handles[thread], 0, customer, (void*)thread); } for(int thread=0; thread<num_customers; thread++) { pthread_join(cust_handles[thread], 0); } printf("Shop closed\\n"); shop_open = 0; pthread_join((void*)barber_handle, 0); return 0; }
1
#include <pthread.h> { pthread_mutex_t lock; pthread_cond_t wait; int value; int waiters; } sema; sema *InitSem(int count) { sema *s; s = (sema *)malloc(sizeof(sema)); if(s == 0) { return(0); } s->value = count; s->waiters = 0; pthread_cond_init(&(s->wait),0); pthread_mutex_init(&(s->lock),0); return(s); } void P(sema *s) { pthread_mutex_lock(&(s->lock)); s->value--; while(s->value < 0) { if(s->waiters < (-1 * s->value)) { s->waiters++; pthread_cond_wait(&(s->wait),&(s->lock)); s->waiters--; } else { break; } } pthread_mutex_unlock(&(s->lock)); return; } void V(sema *s) { pthread_mutex_lock(&(s->lock)); s->value++; if(s->value <= 0) { pthread_cond_signal(&(s->wait)); } pthread_mutex_unlock(&(s->lock)); }
0
#include <pthread.h> const int MAX_THREADS = 1024; void *Thread_function(void* ignore); void Usage(char* prog_name); double elapsed = 0.0; pthread_mutex_t mutex; pthread_barrier_t barrier_p; int main(int argc, char* argv[]) { int thread_count; long thread; pthread_t* thread_handles; if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); pthread_barrier_init(&barrier_p,0,thread_count); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_function, (void *) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); printf("O tempo gasto pela thread mais lenta foi %e segundos\\n", elapsed); pthread_barrier_destroy(&barrier_p); free(thread_handles); pthread_mutex_destroy(&mutex); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads>\\n", prog_name); fprintf(stderr, "0 < number of threads <= %d\\n", MAX_THREADS); exit(0); } void* Thread_function(void* rank) { long my_rank = (long) rank; double my_start, my_finish, my_elapsed; pthread_barrier_wait(&barrier_p); int i; GET_TIME(my_start); for (i = 0; i < 100000; i++); GET_TIME(my_finish); my_elapsed = my_finish - my_start; pthread_mutex_lock(&mutex); if(my_elapsed > elapsed){ elapsed = my_elapsed; } pthread_mutex_unlock(&mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int value = 0; void * signal_after_sometime(void *arg) { if (usleep((int)arg * 1000)) { fprintf(stderr, "error calling usleep\\n"); exit(1); } pthread_mutex_lock(&mutex); value = 1; fprintf(stderr, "signal!\\n"); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); return 0; } void * wait_for_sometime(void *arg) { struct timeval now; struct timespec timeout; long future_us; int r; pthread_mutex_lock(&mutex); gettimeofday(&now, 0); future_us = now.tv_usec + (int)arg * 1000; timeout.tv_nsec = (future_us % 1000000) * 1000; timeout.tv_sec = now.tv_sec + future_us / 1000000; r = 0; while (value == 0 && r != ETIMEDOUT && r != EINVAL && r != EPERM) r = pthread_cond_timedwait(&cond, &mutex, &timeout); if (r == ETIMEDOUT) { printf("timeout!\\n"); exit(0); } else if (r != 0) { printf("error in pthread_cond_timedwait call!\\n"); exit(1); } printf("OK :)\\n"); pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; pthread_create( &t1, 0, &signal_after_sometime, (void*)1000); pthread_create( &t2, 0, &wait_for_sometime, (void*)900); pthread_join( t1, 0); pthread_join( t2, 0); return 0; }
0
#include <pthread.h> int info; char* buffer; } DATA; DATA data; struct Node_t *prev; } NODE; NODE *head; NODE *tail; int size; int limit; int count; int active; } Queue; Queue *ConstructQueue(int limit); void DestructQueue(Queue *queue); int Enqueue(Queue *pQueue, NODE *item); NODE *Dequeue(Queue *pQueue); int isEmpty(Queue* pQueue); Queue *ConstructQueue(int limit) { Queue *queue = (Queue*) malloc(sizeof (Queue)); printf("Memory was allocated for the queue\\n"); if (queue == 0) { return 0; } if (limit <= 0) { limit = 65535; queue->size = 0; } queue->limit = limit; queue->size = 0; queue->count = 0; queue->head = 0; queue->tail = 0; queue->active = 0; return queue; } void DestructQueue(Queue *queue) { NODE *pN; while (!isEmpty(queue)) { pN = Dequeue(queue); free(pN); printf("Memory was freed for the node\\n"); } free(queue); printf("Memory was freed for the queue\\n"); } int Enqueue(Queue *pQueue, NODE *item) { if ((pQueue == 0) || (item == 0)) { return 0; } if (pQueue->size >= pQueue->limit) { return 0; } item->prev = 0; if (pQueue->size == 0) { pQueue->head = item; pQueue->tail = item; } else { pQueue->tail->prev = item; pQueue->tail = item; } pQueue->size++; printf("Queued: %d\\n", item->data.info); return 1; } NODE * Dequeue(Queue *pQueue) { NODE *item; if (isEmpty(pQueue)) return 0; item = pQueue->head; pQueue->head = (pQueue->head)->prev; pQueue->size--; printf("Dequeued: %d\\n", item->data.info); return item; } int isEmpty(Queue* pQueue) { if (pQueue == 0) { return 0; } if (pQueue->size == 0) { return 1; } else{ return 0; } } pthread_mutex_t mtx; void *Thread1(void *x) { int ret; int RandNum; int i; NODE *pN; Queue *pQ = (Queue *)x; pQ->active++; pthread_mutex_unlock(&mtx); printf("Working with the queue\\n"); for (i = 0; i < 10; i++) { RandNum = rand() % 2; if (RandNum){ pN = (NODE*) malloc(sizeof (NODE)); printf("Memory was allocated for the node\\n"); pthread_mutex_lock(&mtx); pN->data.info = 100 + pQ->count; pN->data.buffer = malloc(200 * ( (rand() % 10) + 1) ); pQ->count += 1; ret = Enqueue(pQ, pN); pthread_mutex_unlock(&mtx); if (!ret){ free(pN); printf("Memory was freed for the node\\n"); } } else{ pthread_mutex_lock(&mtx); pN = Dequeue(pQ); pthread_mutex_unlock(&mtx); if (pN){ free(pN->data.buffer); free(pN); printf("Memory was freed for the node\\n"); } } sleep(1); } pthread_mutex_lock(&mtx); pQ->active--; pthread_mutex_unlock(&mtx); printf("Forcing the Dequeue\\n"); return 0; } int main() { int i; Queue *pQ = ConstructQueue(70); pthread_t t[10]; srand(time(0)); pthread_mutex_init(&mtx, 0); for (i = 0; i < 10; i++){ pthread_mutex_lock(&mtx); pthread_create(&t[i], 0, Thread1, pQ); } printf("Waiting for all threads to finish\\n"); while(pQ->active > 0); DestructQueue(pQ); for (i = 0; i < 10; i++) pthread_join(t[i], 0); pthread_mutex_destroy(&mtx); return (0); }
1
#include <pthread.h> static pthread_mutex_t coordinator_mutex; static pthread_cond_t coordinator_cond; static int continuous_mode; static int quickly_mode; static int got_a_location; void init_coordination(int continuous, int quickly) { continuous_mode = continuous; quickly_mode = quickly; got_a_location = 0; pthread_mutex_init(&coordinator_mutex, 0); pthread_cond_init(&coordinator_cond, 0); } void abort_coordination(void) { } int term_coordination(void) { pthread_mutex_destroy(&coordinator_mutex); pthread_cond_destroy(&coordinator_cond); return got_a_location; } int already_done(void) { int rc = continuous_mode; pthread_mutex_lock(&coordinator_mutex); rc &= got_a_location; pthread_mutex_unlock(&coordinator_mutex); return rc; } void run(int argc, char** argv) { if (!strcmp(*argv, "cache")) guess_by_cache(); else if (!strcmp(*argv, "timezone-offset")) guess_by_timezone_offset(); else if (!strcmp(*argv, "manual")) guess_by_manual(argv + 1); else if (!strcmp(*argv, "read")) guess_by_file(argc - 1, argv + 1); else if (!strcmp(*argv, "spawn")) guess_by_command(argc - 1, argv + 1); free(*argv); free(argv); } int may_i_report(int async) { int rc = async; pthread_mutex_lock(&coordinator_mutex); if ((rc |= quickly_mode)) got_a_location = 1; quickly_mode = 0; pthread_mutex_unlock(&coordinator_mutex); return rc; }
0
#include <pthread.h> int global_variable_count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void* IncrementVariable(void *id) { int i; int threadID = (int)id; printf("Starting IncrementVariable(): thread %d\\n", threadID); for (i=0; i < 5; i++) { pthread_mutex_lock(&count_mutex); global_variable_count++; if (global_variable_count == 8) { pthread_cond_signal(&count_threshold_cv); printf("IncrementVariable(): thread %d, count = %d Limit reached.\\n", threadID, global_variable_count); } printf("IncrementVariable(): thread %d, incrementing count, count = %d, unlocking mutex\\n", threadID, global_variable_count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void* WatchVariable(void *id) { int threadID = (int)id; printf("Starting WatchVariable(): thread %d\\n", threadID); pthread_mutex_lock(&count_mutex); while (global_variable_count < 8) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("WatchVariable(): thread %d Condition signal received.\\n", threadID); global_variable_count += 1000; printf("WatchVariable(): thread %d count now = %d.\\n", threadID, global_variable_count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i; 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_create(&threads[0], &attr, WatchVariable, (void *)1); pthread_create(&threads[1], &attr, IncrementVariable, (void *)2); pthread_create(&threads[2], &attr, IncrementVariable, (void *)3); for (i=0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Done.\\n"); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); return 1; }
1
#include <pthread.h> void generar_persona (); void cerrar_banio (int ids); void generar_mujer (); void generar_hombre (); void * mujer (void * arg); void * hombre (void * arg); void mujer_quiere_entrar (); void hombre_quiere_entrar (); void mujer_sale (); void hombre_sale (); void * sacarPersona (void * arg); int personasEnBanio = 0; int hombresEnEspera = 0; int mujeresEnEspera = 0; int tipodDeBanio = 0; int abierto = 1; pthread_mutex_t mutexBanio = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexMujeresEnEspera = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexHombresEnEspera = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t esperandoBanio = PTHREAD_COND_INITIALIZER; int main(int argc, char const *argv[]) { srand((int)time(0)); printf("Sanitario vacio\\n"); pthread_t salidas; pthread_create(&salidas,0,sacarPersona, 0); while (abierto){ generar_persona(); sleep(3); } pthread_exit(0); return 0; } void cerrar_banio (int ids){ printf("Cerrando baño...\\n"); abierto = 0; } void generar_persona () { int tipoPersona = (rand() % 2) + 1; if (tipoPersona == 1){ generar_mujer(); } else { generar_hombre(); } } void * mujer (void * arg){ mujer_quiere_entrar(); pthread_exit(0); } void * hombre (void * arg){ hombre_quiere_entrar(); pthread_exit(0); } void generar_mujer (){ pthread_t pMujer; pthread_create(&pMujer,0, mujer,(void *)1); } void generar_hombre (){ pthread_t pHombre; pthread_create(&pHombre,0, hombre,(void *)2); } void mujer_quiere_entrar (){ int imprimir; int esperando = 1; pthread_mutex_lock(&mutexMujeresEnEspera); mujeresEnEspera++; printf("Llega mujer (%d en espera)\\n", mujeresEnEspera); pthread_mutex_unlock(&mutexMujeresEnEspera); while (esperando){ pthread_mutex_lock(&mutexBanio); imprimir = tipodDeBanio == 2 && personasEnBanio == 0; if (tipodDeBanio == 1 || tipodDeBanio == 0 || (tipodDeBanio == 2 && personasEnBanio == 0)){ tipodDeBanio = 1; personasEnBanio++; mujeresEnEspera--; printf("Entra una mujer (%d en espera)\\n",mujeresEnEspera); esperando = 0; } else { printf("Mujer esperando el baño\\n"); pthread_cond_wait(&esperandoBanio, &mutexBanio); } pthread_mutex_unlock(&mutexBanio); if (imprimir) { printf("Baño ocupado por mujeres\\n"); } } } void * sacarPersona (void * arg){ while (abierto){ pthread_mutex_lock(&mutexBanio); if (personasEnBanio > 0){ if (tipodDeBanio == 1 ){ mujer_sale(); } else { hombre_sale(); } if (personasEnBanio == 0){ printf("Sanitario vacio\\n"); } } pthread_mutex_unlock(&mutexBanio); sleep(5); } pthread_exit(0); } void hombre_quiere_entrar (){ int imprimir; int esperando = 1; pthread_mutex_lock(&mutexHombresEnEspera); hombresEnEspera++; printf("Llega hombre (%d en espera)\\n", hombresEnEspera); pthread_mutex_unlock(&mutexHombresEnEspera); while(esperando){ pthread_mutex_lock(&mutexBanio); imprimir = tipodDeBanio == 1 && personasEnBanio == 0; if (tipodDeBanio == 2 || tipodDeBanio == 0 || (tipodDeBanio == 1 && personasEnBanio == 0)){ tipodDeBanio = 2; personasEnBanio++; hombresEnEspera--; printf("Entra un hombre (%d en espera)\\n",hombresEnEspera); esperando = 0; } else { printf("Hombre esperando el baño\\n"); pthread_cond_wait(&esperandoBanio, &mutexBanio); } pthread_mutex_unlock(&mutexBanio); if (imprimir) { printf("Baño ocupado por hombres\\n"); } } } void mujer_sale (){ personasEnBanio--; printf("Sale una mujer\\n"); } void hombre_sale () { personasEnBanio--; printf("Sale un hombre\\n"); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void* child1( void* param ) { pthread_cleanup_push( (void (*)(void*))pthread_mutex_unlock, (void*)&mutex ); while( 1 ) { printf( "thread 1 get running\\n" ); printf( "thread 1 pthread_mutex_lock returns %d\\n", pthread_mutex_lock( &mutex )); pthread_cond_wait( &cond, &mutex ); printf( "thread 1 condition applied\\n" ); pthread_mutex_unlock( &mutex ); sleep( 5 ); } pthread_cleanup_pop( 0 ); return ( void* )0; } void* child2( void* param ) { while( 1 ) { sleep( 3 ); printf( "thread 2 get running\\n" ); printf( "thread 2 pthread_mutex_lock returns %d\\n", pthread_mutex_lock( &mutex ) ); pthread_cond_wait( &cond, &mutex ); printf( "thread 2 condition applied\\n" ); pthread_mutex_unlock( &mutex ); sleep( 1 ); } return ( void* )0; } int main() { pthread_t tid1, tid2; printf( "hello, condition variable test\\n" ); pthread_mutex_init( &mutex, 0 ); pthread_cond_init( &cond, 0 ); pthread_create( &tid1, 0, child1, 0 ); pthread_create( &tid2, 0, child2, 0 ); do { sleep( 2 ); pthread_cancel( tid1 ); sleep( 2 ); pthread_cond_signal( &cond ); }while( 1 ); sleep( 100 ); pthread_exit( 0 ); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexB; pthread_mutex_t mutexC; pthread_mutex_t mutexD; pthread_mutex_t mutexE; void *f(void *unused) { pthread_mutex_lock(&mutexA); pthread_mutex_lock(&mutexB); pthread_mutex_unlock(&mutexB); pthread_mutex_unlock(&mutexA); return 0; } int main() { pthread_t t; pthread_mutex_init(&mutexB, 0); pthread_mutex_init(&mutexC, 0); pthread_mutex_init(&mutexD, 0); pthread_mutex_init(&mutexE, 0); pthread_create(&t, 0, f, 0); pthread_mutex_lock(&mutexA); pthread_mutex_lock(&mutexB); pthread_mutex_unlock(&mutexB); pthread_mutex_lock(&mutexC); pthread_mutex_unlock(&mutexC); pthread_mutex_unlock(&mutexA); pthread_mutex_lock(&mutexC); pthread_mutex_unlock(&mutexC); pthread_mutex_lock(&mutexD); pthread_mutex_unlock(&mutexD); pthread_mutex_lock(&mutexE); pthread_mutex_lock(&mutexD); pthread_mutex_unlock(&mutexD); pthread_join(t, 0); printf("Send process %d a SIGUSR1 signal 'kill -SIGUSR1 %d'\\n", getpid(), getpid()); sleep(1000); return 1; }
0
#include <pthread.h> void initGrid(int grid[ROW][ROW]){ int i,j; for (i=0; i< ROW; i++){ for (j=0; j< ROW; j++){ grid[i][j]=0; } } } void initNetwork(pthread_mutex_t network[ROW][ROW]){ int i,j,rc; for (i=0; i<ROW; i++){ for (j=0; j<ROW; j++){ rc = pthread_mutex_init(&network[i][j], 0); assert(rc==0); } } } void printGrid(int grid[ROW][ROW]){ int i,j; for (i=0; i< ROW; i++){ for (j=0; j< ROW; j++){ printf("%d ",grid[i][j]); } printf("\\n"); } } void initRand(){ time_t t; srand((unsigned) time(&t)); } int myRand(){ return rand() % ROW; } void initPacket(struct Packet * p_message){ p_message->src_x = myRand(); p_message->src_y = myRand(); p_message->dst_x = myRand(); p_message->dst_y = myRand(); if ( (p_message->src_x == p_message->dst_x) && (p_message->src_y == p_message->dst_y) ){ p_message->dst_x = (p_message->dst_x + 1 )% ROW; p_message->dst_y = (p_message->dst_y + 1 )% ROW; } } void printPacket(struct Packet * p_message){ printf("(%d,%d)src to (%d,%d)dst\\n",p_message->src_x, p_message->src_y, p_message->dst_x, p_message->dst_y); } int next_hop_value(int now, int next){ return ( now < next ) ? ( (now+1)%ROW ) : ( (now-1)%ROW ) ; } void traverse_network(struct Packet * p_message, pthread_mutex_t network_grid[ROW][ROW], int t_id ){ int x_tmp = p_message->src_x; int y_tmp = p_message->src_y; int x_dst = p_message->dst_x; int y_dst = p_message->dst_y; int x_nxt = x_tmp; int y_nxt = y_tmp; int local_id = t_id+1; printf("ID %d:\\t",local_id); printPacket(p_message); pthread_mutex_lock( &network_grid[x_tmp][y_tmp]); while ( x_tmp != x_dst || y_tmp != y_dst ){ if (x_tmp != x_dst){ x_nxt = next_hop_value(x_tmp, x_dst); assert(x_nxt != -1); } else{ y_nxt = next_hop_value(y_tmp, y_dst); assert(y_nxt != -1); } printf("\\t(%d,%d)tmp -> (%d,%d)nxt\\n",x_tmp,y_tmp,x_nxt,y_nxt); pthread_mutex_lock( &network_grid[x_nxt][y_nxt]); pthread_mutex_unlock( &network_grid[x_tmp][y_tmp]); x_tmp = x_nxt; y_tmp = y_nxt; } pthread_mutex_unlock( &network_grid[x_tmp][y_tmp]); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int x; void producer(void) { while(1){ pthread_mutex_lock(&mutex); int i; for(i=0; i<3-x; i++){ x++; printf("Producing : x=%d \\n", x); sleep(1); } if(x >= 3){ pthread_cond_signal(&cond); printf("Producing completed.\\n", x); } pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void consumer(void) { while(1){ pthread_mutex_lock(&mutex); while(x < 3){ pthread_cond_wait(&cond, &mutex); printf("Start consuming.\\n"); } while(x > 0){ x--; printf("Consuming : x=%d \\n", x); sleep(1); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(void) { pthread_t id1, id2; int ret; ret = pthread_mutex_init(&mutex, 0); if(ret != 0){ printf("Mutex initialization failed.\\n"); exit(1); } ret = pthread_cond_init(&cond, 0); if(ret != 0){ printf("Conditions initialization failed.\\n"); exit(1); } ret = pthread_create(&id1, 0, (void *)&producer, 0); if(ret != 0){ printf("Thread Producer create failed.\\n"); exit(1); } ret = pthread_create(&id2, 0, (void *)&consumer, 0); if(ret != 0){ printf("Thread Consumer create failed.\\n"); exit(1); } pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int power_modulo_fast(int a, int b, int m) { int i; int result = 1; long int x = a%m; for (i=1; i<=b; i<<=1) { x %= m; if ((b&i) != 0) { result *= x; result %= m; } x *= x; } return result%m; } int Fermat(int n, int k) { int a, i; srand(time(0)); if (n<4) { return 1; } for (i=0; i<k; i++) { a = 2+(int) ((n-2)*rand()/(32767 +1.0)); if (power_modulo_fast(a, n-1, n) != 1) { return 0; } } return 1; } pthread_t tid[5]; int pocz; int kon; int numer; } par_t; void *findPrimes(void *arg) { par_t *bounds = (par_t*)arg; bounds->numer = pthread_self(); printf( "This is thread %d\\n", bounds->numer ); int i = 0; int zd = (int)bounds->pocz; int zg = (int)bounds->kon; printf("in findPrimes zd : %d, zg : %d\\n", zd, zg ); int arrayLength = zg - zd; int primeNumbers[arrayLength]; int input[arrayLength]; for(; zd < zg; zd++ ){ input[i] = zd; i++; } int n = 0; int k = 1; int j = 0; for(i = 0; i < zg; i++){ n = input[i]; if (Fermat(n, k) == 1) { primeNumbers[j] = n; pthread_mutex_lock( &mutex ); j++; pthread_mutex_unlock( &mutex ); } } int counter = 0; for(i = 0; i < j - 1; i++){ if(primeNumbers[i] > 0) counter++; } return (void*) counter; } int main(int argc, char *argv[]) { int numThreads = atoi(argv[3]) ; int zd = atoi(argv[1]); int zg = atoi(argv[2]); int arrayLength = zg - zd; par_t *pBounds = malloc(sizeof(par_t) ); int status; int temp = 0; int i = 0; for(i=0; i < numThreads ; i++){ pBounds->pocz = zd; pBounds->kon = (int)(zg/numThreads) + temp; temp = pBounds->kon; zd = pBounds->kon; printf("ranges : %d - %d\\n", pBounds->pocz, pBounds->kon); pthread_create(&tid[i],0,findPrimes,(void*) pBounds ); } for(i=0; i < numThreads ; i++) { pthread_join(tid[i],(void*)&status); printf("watek %d zakonczony, w zadanym przedziale znalazl %d liczb pierwszych\\n",tid[i],status); } return 0; }
1
#include <pthread.h> void func1(); void func2(); void func3(); pthread_cond_t cond,cond2; pthread_mutex_t mutex; int main() { pthread_t thread[2]; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_cond_init(&cond2,0); int i=0; int *status; void (*funcptr[3])(); funcptr[0]=func1; funcptr[1]=func2; funcptr[2]=func3; for (i=0;i<3;i++) { if(pthread_create(&thread[i],0,(void *)funcptr[i],0)) { printf("thread %ld failed to create",thread[i]); } } for (i=0;i<3;i++) pthread_join(thread[i],(void*)&status); pthread_exit(0); return 0; } void func1() { pthread_mutex_lock(&mutex); printf("I am producer\\n"); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } void func2() { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("I am consumer\\n"); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond2); } void func3() { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond2,&mutex); printf("I am in 3rd thread\\n"); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> struct s_c_c { unsigned int msg_type; unsigned int msg_len; unsigned char msg[1]; }; struct stalker_info { pthread_t stalker; void *mq; pthread_mutex_t mut; pthread_cond_t cond; unsigned int status; unsigned int (*thread_worker)(void *si, void *pi); void *exptr; }; unsigned int worker_null(void *si, void *pi) { return 0; } unsigned int thread_wakeup(struct stalker_info *si) { if(0 == si->status) { pthread_mutex_lock(&(si->mut)); si->status = 1; pthread_cond_signal(&si->cond); pthread_mutex_unlock(&(si->mut)); } return 1; } unsigned int thread_sleep(struct stalker_info *si) { if(1 == si->status) { pthread_mutex_lock(&(si->mut)); si->status = 0; while(0 == si->status) pthread_cond_wait(&(si->cond), &(si->mut)); pthread_mutex_unlock(&(si->mut)); } return 1; } unsigned int thread_loop(struct stalker_info *si) { struct s_c_c *cm = 0; unsigned int len = 0; unsigned int ret = 0; for(;;) { cm = 0; ret = queue_read_message(si->mq, &cm, &len, 0); if(QUEUE_END == ret) { return 0; } else if(QEUUE_NO_MSG == ret || 0 == cm) { return 1; } switch(cm->msg_type) { case 1: si->thread_worker = (int(*)(void*))( *((void**)(cm->msg)) ); break; case 2: si->thread_worker = worker_null; break; case 3: return 0; break; case 4: if(0 == (*(si->thread_worker))(si, *((void**)(cm->msg)) ) ) return 0; break; default: break; } } } void* thread_main(struct stalker_info *si) { while( thread_loop(si) && thread_sleep(si) ); return 0; } unsigned int thread_exit(pthread_t t) { if(!t) return 1; pthread_cancel(t); pthread_join(t, 0); return 1; } void si_free(struct stalker_info *si) { if(!si) return; if(si->stalker) { thread_exit(si->stalker); } if(si->mq) { si->mq = queue_destory(si->mq); } } struct stalker_info* si_malloc(void) { struct stalker_info *si = 0; unsigned int size = sizeof(struct stalker_info); si = malloc(size); if(0 == si) goto fail_return; memset(si, 0, size); si->mq = queue_create(0, 0); if(0 == si->mq) goto fail_return; si->thread_worker = worker_null; if(0 != pthread_create(&(si->stalker), 0, thread_main, si)) goto fail_return; pthread_mutex_init(&(si->mut), 0); pthread_cond_init(&(si->cond), 0); si->status = 1; success_return: return si; fail_return: si_free(si); return 0; } void* stalker_create(void) { struct stalker_info *si = si_malloc(); return si; } unsigned int do_push_ptr(struct stalker_info *si, unsigned int msg_type, void *ptr) { if(!si) return 0; union { unsigned char buf[sizeof(struct s_c_c) + 4]; struct s_c_c cm; }umsg; umsg.cm.msg_type = msg_type; umsg.cm.msg_len = sizeof(ptr); memcpy(umsg.cm.msg, &ptr, umsg.cm.msg_len); queue_write_message(si->mq, &umsg, sizeof(umsg), 0); return 1; } unsigned int stalker_set_callback(void *si, unsigned int(*callback)(void*,void*)) { return do_push_ptr(si, 1, callback) && thread_wakeup(si); } unsigned int stalker_set_callback_null(void *si) { return do_push_ptr(si, 2, 0) && thread_wakeup(si); } unsigned int stalker_push_new_ptr(void *si, void *ptr) { return do_push_ptr(si, 4, ptr) && thread_wakeup(si); } unsigned int stalker_stop(void *si) { return do_push_ptr(si, 3, 0) && thread_wakeup(si); } unsigned int do_wirte_end(struct stalker_info *si) { return si ? queue_write_end(si->mq) : 0; } unsigned int stalker_stop_until_no_msg(void *si) { return do_wirte_end(si) && thread_wakeup(si); } unsigned int stalker_set_exptr(void *si, void *ptr) { return si ? ((struct stalker_info*)si)->exptr = ptr : 0; } void* stalker_get_exptr(void *si) { return si ? ((struct stalker_info*)si)->exptr : 0; }
1
#include <pthread.h> extern int pthread_setconcurrency(int); extern int pthread_getconcurrency(); struct { pthread_mutex_t data_lock[5]; int int_val[5]; double double_val[5]; } data; void *add_to_value(); int main() { puts("arrays - POSIX version"); pthread_t thr[5]; puts("init.."); int idx=0; for(idx = 0; idx < 5; ++idx){ if(0 != pthread_mutex_init((void*) &data.data_lock[idx], 0)){ perror("pthread_mutex_lock failed"); exit(1); } data.int_val[idx] = 0; data.double_val[idx] = 0.0; } printf("the current level is %d set the concurrency level to 4\\n", pthread_getconcurrency()); pthread_setconcurrency(4); puts("creating threads"); for(idx = 0; idx < 5; ++idx){ if(0 != pthread_create( (void*) &thr[idx], 0, add_to_value, (void*) (2*idx))){ perror("pthread_create failed:"); exit(1); } } puts("joining threads"); for(idx = 0; idx < 5; ++idx){ int* status=0; pthread_join(thr[idx], (void*) &status); if(status == 0){ fprintf(stderr, "ERROR: thread %d failed\\n", idx); exit(1); } } printf("Final Values.....\\n"); for(idx = 0; idx < 5; ++idx){ printf("integer value[%d] =\\t%d\\n", idx, data.int_val[idx]); printf("double value[%d] =\\t%.1f\\n\\n", idx, data.double_val[idx]); } puts("clean up.."); for(idx = 0; idx < 5; ++idx){ pthread_mutex_destroy((void*) &data.data_lock[idx]); } puts("READY."); exit(0); } void *add_to_value(void *arg) { int inval = (int) arg; printf("\\nthread %d: was called..\\nlock\\taction\\n", (inval/2)); int idx = 0; for(idx = 0; idx < 5; ++idx){ pthread_mutex_lock(&data.data_lock[idx % 5]); printf("\\n%d -\\tthread %d: locked!\\n", (inval/2), (inval/2)); printf("%d -\\tidx(%d): %d += %d ", (inval/2), (idx % 5), data.int_val[idx % 5], inval); data.int_val[idx % 5] += inval; printf("= %d\\n", data.int_val[idx % 5]); printf("%d -\\tidx(%d): %.1f += %.1f ", (inval/2), (idx % 5), data.double_val[idx % 5], ((double) 1.5 * inval)); data.double_val[idx % 5] += (double) 1.5 * inval; printf("= %.1f\\n", data.double_val[idx % 5]); printf("%d -\\tthread %d: unlockes!\\n", (inval/2), (inval/2)); pthread_mutex_unlock(&data.data_lock[idx % 5]); } printf("%d -\\tthread %d: exits\\n", (inval/2), (inval/2)); pthread_exit((void*) 5); }
0
#include <pthread.h> double sum; pthread_mutex_t sumMutex; int id; int sliceSize; double delta; } CalculationParameters; void * partialSum(void *const arg ) { int const start = 1 + ((CalculationParameters *const)arg)->id * ((CalculationParameters *const)arg)->sliceSize; int const end = (((CalculationParameters *const)arg)->id + 1) * ((CalculationParameters *const)arg)->sliceSize; double const delta = ((CalculationParameters *const)arg)->delta; double localSum = 0.0; for (int i = start; i <= end; ++i) { double const x = (i - 0.5) * delta; localSum += 1.0 / (1.0 + x * x); } pthread_mutex_lock(&sumMutex); sum += localSum; pthread_mutex_unlock(&sumMutex); pthread_exit((void *) 0); return 0; } void execute(int const numberOfThreads) { int const n = 1000000000; double const delta = 1.0 / n; long long const startTimeMicros = microsecondTime(); int const sliceSize = n / numberOfThreads; pthread_mutex_init(&sumMutex, 0); pthread_attr_t attributes; pthread_attr_init(&attributes); pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_JOINABLE); sum = 0.0; pthread_t threads[numberOfThreads]; CalculationParameters parameters[numberOfThreads]; for (int i = 0; i < numberOfThreads; ++i) { parameters[i].id = i; parameters[i].sliceSize = sliceSize; parameters[i].delta = delta; if (pthread_create (&threads[i], &attributes, partialSum, (void *)&parameters[i]) != 0) { exit(1); } } pthread_attr_destroy(&attributes); int status; for (int i = 0; i < numberOfThreads; ++i) { pthread_join(threads[i], (void **)&status); } double const pi = 4.0 * delta * sum; double const elapseTime = (microsecondTime() - startTimeMicros) / 1e6; outn("PThread Parameters", pi, n, elapseTime, numberOfThreads, sysconf(_SC_NPROCESSORS_ONLN)); } int main() { execute(1); execute(2); execute(8); execute(32); return 0; }
1
#include <pthread.h> int thread_status = 0; pthread_mutex_t mutex; pthread_cond_t cond; void *rand_input(void *arg) { if(!arg) { printf("\\nERR:INVALID input argument to thread\\n"); pthread_exit(0); } printf("\\nrand_input pthread self ID : %lu\\n", pthread_self()); while(1) { pthread_mutex_lock(&mutex); if(!thread_status) { printf("\\n Entering input Thread\\n"); int *input = (int*)arg; int size = 50; if(!input) { printf("Invalid Input buffer for random data loading! Retry! \\n"); exit(0); } int i = 0; for (i=0;i<size;i++) *(input+i) = rand()%size; printf("\\nInput Buffer\\n"); for(i = 0 ;i<size-1;i++) { printf("%d,",*(input+i)); } *(input+size-1)=22; for (i=0;i<size;i++) { if(*(input+i) == 22) { pthread_cond_signal(&cond); thread_status = 1; pthread_mutex_unlock(&mutex); } } break; } } return 0; } void *ltos_sort(void *arg) { if(!arg) { printf("\\nERR:INVALID input argument to thread\\n"); pthread_exit(0); } printf("\\nltos_sort pthread self ID : %lu\\n", pthread_self()); while(1) { if(!pthread_mutex_trylock(&mutex)) { pthread_cond_wait( &cond, &mutex); if(thread_status) { int outer,inner,temp = 0; int size = 50; int i =0; int *input = (int *)arg; for(outer =0;outer<size;outer++) { for(inner = outer+1;inner<=size;inner++) { if(*(input+outer) < *(input+inner)) { temp = *(input+outer); *(input+outer) = *(input+inner); *(input + inner) = temp; } } } pthread_mutex_unlock(&mutex); break; } } } return 0; } int main() { int i =0; int result = 0; long long stacksize=0; int *buffer = malloc(100*sizeof(int)); if(!buffer) { printf("\\n Malloc Failed \\n"); exit(0); } pthread_t rinput_thread,sort_thread; pthread_attr_t attr; printf("Enter stack size(greate than or equal to 0:)"); scanf("%lld",&stacksize); if(stacksize>=0) { result = pthread_attr_setstacksize(&attr,stacksize); if(!result) printf("ERR:In setting stack size\\n"); } else { printf("\\nERR:INVALID STACK SIZE! Exiting!\\n"); exit(0); } if(pthread_mutex_init(&mutex,0) != 0) { printf("\\nERR:Mutex Init Failed!\\n"); return 1; } if(pthread_cond_init(&cond,0) != 0) { printf("\\nERR:Condition Init Failed!\\n"); return 1; } if(pthread_getattr_default_np(&attr) !=0) { printf("\\nERR:get attribute default Failed!\\n"); return 1; } if(pthread_create(&rinput_thread,&attr, &rand_input,(void *)buffer) != 0) { printf("\\nERR:Thread Creation Failed!\\n"); return 1; } if(pthread_create(&sort_thread, &attr, &ltos_sort, (void *)buffer) != 0) { printf("\\nERR:Thread Creation Failed!\\n"); return 1; } if(result = pthread_getattr_np(rinput_thread,&attr) != 0) { printf("\\nERR:get attribute Failed!\\n"); return 1; } printf("\\n Result of successfull getattr %d\\n"); if(pthread_join(rinput_thread, 0) != 0) { printf("\\nERR:Thread Joining Failed!\\n"); return 1; } if(pthread_join(sort_thread, 0) != 0) { printf("\\nERR:Thread Joining Failed!\\n"); return 1; } printf("\\n\\nSorted buffer\\n"); for(i = 0; i<50; i++) { printf("%d,",*(buffer+i)); } printf("\\n"); pthread_exit(0); if(pthread_mutex_destroy(&mutex) != 0) { printf("\\nERR:Mutex destroy Failed!\\n"); return 1; } if(pthread_cond_destroy(&cond) !=0) { printf("\\nERR:Condition destroy Failed!\\n"); return 1; } free(buff); return 0; }
0
#include <pthread.h> int pbs_terminate_err( int c, int manner, char *extend, int *local_errno) { struct batch_reply *reply; int rc = 0; int sock; struct tcp_chan *chan = 0; pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { pthread_mutex_unlock(connection[c].ch_mutex); rc = PBSE_PROTOCOL; return rc; } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_Shutdown, pbs_current_user)) || (rc = encode_DIS_ShutDown(chan, manner)) || (rc = encode_DIS_ReqExtend(chan, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return(PBSE_PROTOCOL); } if (DIS_tcp_wflush(chan)) { pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return(PBSE_PROTOCOL); } reply = PBSD_rdrpy(local_errno, c); rc = connection[c].ch_errno; pthread_mutex_unlock(connection[c].ch_mutex); PBSD_FreeReply(reply); DIS_tcp_cleanup(chan); return(rc); } int pbs_terminate( int c, int manner, char *extend) { pbs_errno = 0; return(pbs_terminate_err(c, manner, extend, &pbs_errno)); }
1
#include <pthread.h> struct telnet_info_node { int controlId; char *ip_addr; int port; int id; TELNET_INFO_NODE prev; TELNET_INFO_NODE next; }; static TELNET_INFO_NODE g_telnet_info_node_head = 0; static pthread_mutex_t g_telnet_info_mutex = PTHREAD_MUTEX_INITIALIZER; static TELNET_INFO_NODE make_telnet_info_node() { TELNET_INFO_NODE lp_node = (TELNET_INFO_NODE)malloc(sizeof(struct telnet_info_node)); if(!lp_node) return 0; lp_node->ip_addr = 0; lp_node->prev = 0; lp_node->next = 0; return lp_node; } static void free_telnet_info_node(TELNET_INFO_NODE lp_node) { if(lp_node->ip_addr) free(lp_node->ip_addr); free(lp_node); } static void insert_telnet_info_node(TELNET_INFO_NODE *head, TELNET_INFO_NODE lp_node) { if(*head == 0) { lp_node->prev = 0; lp_node->next = 0; *head = lp_node; } else { lp_node->next = *head; (*head)->prev = lp_node; *head = lp_node; lp_node->prev = 0; } } static TELNET_INFO_NODE interval_search_telnet_info_node(TELNET_INFO_NODE *head, int controlId) { TELNET_INFO_NODE node; if(!(*head)) return 0; printf("%s, controlId %d\\n", __FUNCTION__, controlId); node = *head; while(node) { if(node->controlId == controlId) { printf("%s, node->controlId %d\\n", __FUNCTION__, node->controlId); return node; } node = node->next; } return 0; } static int interval_delete_telnet_info_node(TELNET_INFO_NODE *head, int controlId) { TELNET_INFO_NODE node; if(!(*head)) return 0; node = *head; while(node) { if(node->controlId == controlId) { TELNET_INFO_NODE temp_node; if(node->prev) node->prev->next = node->next; if(node->next) node->next->prev = node->prev; temp_node = node; node = node->next; if(*head == temp_node) *head = node; free_telnet_info_node(temp_node); return 1; } node = node->next; } return 0; } static int interval_add_telnet_info_node(TELNET_INFO_NODE *head, int controlId, const char *ip_address, int port, int id) { int len; TELNET_INFO_NODE lp_node; if(!ip_address) return 0; while(1) { lp_node = interval_search_telnet_info_node(head, controlId); if(!lp_node) break; printf("warning : redundant telnet_info_node\\n"); interval_delete_telnet_info_node(head, controlId); } lp_node = make_telnet_info_node(); if(0 == lp_node) return 0; lp_node->controlId = controlId; lp_node->port = port; lp_node->id = id; len = strlen(ip_address); lp_node->ip_addr = (char *)malloc(len + 1); strcpy(lp_node->ip_addr, ip_address); lp_node->ip_addr[len] = '\\0'; insert_telnet_info_node(&g_telnet_info_node_head, lp_node); return 1; } TELNET_INFO_NODE search_telnet_info_node(int controlId) { TELNET_INFO_NODE lp_node; pthread_mutex_lock(&g_telnet_info_mutex); lp_node = interval_search_telnet_info_node(&g_telnet_info_node_head, controlId); pthread_mutex_unlock(&g_telnet_info_mutex); return lp_node; } int get_telnet_info_node_id(int controlId) { TELNET_INFO_NODE lp_node = search_telnet_info_node(controlId); if(0 == lp_node) return -1; return lp_node->id; } int delete_telnet_info_node(int controlId) { int result; pthread_mutex_lock(&g_telnet_info_mutex); result = interval_delete_telnet_info_node(&g_telnet_info_node_head, controlId); pthread_mutex_unlock(&g_telnet_info_mutex); return result; } int add_telnet_info_node(int controlId, const char *ip_address, int port, int id) { int result; pthread_mutex_lock(&g_telnet_info_mutex); result = interval_add_telnet_info_node(&g_telnet_info_node_head, controlId, ip_address, port, id); pthread_mutex_unlock(&g_telnet_info_mutex); return result; }
0
#include <pthread.h> pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER; int done = 0; int todo = 0; double wtime(void); void* thread1_fn(void* foo); void wakeywakey(void); double wtime(void) { struct timeval t; gettimeofday(&t, 0); return((double)t.tv_sec + (double)t.tv_usec / 1000000); } void* thread1_fn(void* foo) { int ret = -1; while(1) { pthread_mutex_lock(&mut1); while(todo == 0) { ret = pthread_cond_wait(&cond1, &mut1); assert(ret == 0); } todo = 0; pthread_mutex_unlock(&mut1); pthread_mutex_lock(&mut2); done = 1; pthread_mutex_unlock(&mut2); pthread_cond_signal(&cond2); } } void wakeywakey(void) { int ret = -1; pthread_mutex_lock(&mut1); todo = 1; pthread_mutex_unlock(&mut1); pthread_cond_signal(&cond1); pthread_mutex_lock(&mut2); while(done == 0) { ret = pthread_cond_wait(&cond2, &mut2); assert(ret == 0); } done = 0; pthread_mutex_unlock(&mut2); } int main(int argc, char **argv) { pthread_t thread1; int ret = -1; int i = 0; double time1, time2; ret = pthread_create(&thread1, 0, thread1_fn, 0); assert(ret == 0); time1 = wtime(); for(i=0; i<100000; i++) { wakeywakey(); } time2 = wtime(); printf("time for %d iterations: %f seconds.\\n", 100000, (time2-time1)); printf("per iteration: %f\\n", (time2-time1)/(double)100000); return(0); }
1
#include <pthread.h> pthread_t tid; pthread_mutex_t mutex; pthread_cond_t cond; void *arg; }thdinfo_t; void *led_cntl(void *arg); void *gprs_cntl(void *arg); void *camera_cntl(void *arg); void *firehydrant_cntl(void *arg); void *alarm_cntl(void *arg); int warn_flag; int main() { void *(*pthread_handlers[])(void *) = { led_cntl, gprs_cntl, camera_cntl, firehydrant_cntl, alarm_cntl, }; const int THDNO = sizeof(pthread_handlers) / sizeof(*pthread_handlers); thdinfo_t *thdinfo_buff = 0; int index; char cmd[16]; thdinfo_buff = (thdinfo_t *)malloc(sizeof(thdinfo_t) * THDNO); for (index = 0; index < THDNO; index ++) { pthread_mutex_init(&thdinfo_buff[index].mutex, 0); pthread_cond_init(&thdinfo_buff[index].cond, 0); } for (index = 0; index < THDNO; index ++) pthread_create( &thdinfo_buff[index].tid, 0, pthread_handlers[index], thdinfo_buff + index); while (1) { puts("enter your command:"); fgets(cmd, 16, stdin); switch (cmd[0]) { case 'f': warn_flag = 'F'; pthread_cond_signal(&thdinfo_buff[1].cond); pthread_cond_signal(&thdinfo_buff[4].cond); pthread_cond_signal(&thdinfo_buff[3].cond); break; case 't': warn_flag = 'T'; pthread_cond_signal(&thdinfo_buff[1].cond); pthread_cond_signal(&thdinfo_buff[4].cond); pthread_cond_signal(&thdinfo_buff[0].cond); pthread_cond_signal(&thdinfo_buff[2].cond); break; case 'c': warn_flag = 0; break; case 'q': goto Quit; default: puts("command error !"); break; } } for (index = 0; index < THDNO; index ++) pthread_join(thdinfo_buff[index].tid, 0); Quit: for (index = 0; index < THDNO; index ++) { pthread_cancel(thdinfo_buff[index].tid); } free(thdinfo_buff); exit(0); return 0; } void *led_cntl(void *arg) { thdinfo_t *info = arg; while (1) { pthread_mutex_lock(&info->mutex); pthread_cond_wait(&info->cond, &info->mutex); pthread_mutex_unlock(&info->mutex); while (warn_flag) { puts("---------- led -----------"); sleep(1); } } } void *gprs_cntl(void *arg) { thdinfo_t *info = arg; while (1) { pthread_mutex_lock(&info->mutex); pthread_cond_wait(&info->cond, &info->mutex); pthread_mutex_unlock(&info->mutex); while (warn_flag) { puts("---------- gprs -----------"); sleep(1); } } } void *camera_cntl(void *arg) { thdinfo_t *info = arg; while (1) { pthread_mutex_lock(&info->mutex); pthread_cond_wait(&info->cond, &info->mutex); pthread_mutex_unlock(&info->mutex); while (warn_flag) { puts("---------- camera -----------"); sleep(1); } } } void *firehydrant_cntl(void *arg) { thdinfo_t *info = arg; while (1) { pthread_mutex_lock(&info->mutex); pthread_cond_wait(&info->cond, &info->mutex); pthread_mutex_unlock(&info->mutex); while (warn_flag) { puts("---------- firehydrant -----------"); sleep(1); } } } void *alarm_cntl(void *arg) { thdinfo_t *info = arg; while (1) { pthread_mutex_lock(&info->mutex); pthread_cond_wait(&info->cond, &info->mutex); pthread_mutex_unlock(&info->mutex); while (warn_flag) { puts("---------- alarm -----------"); sleep(1); } } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int compare(const int * a, const int * b){ if (*a > *b){ return(1); } else if( *b > *a){ return(-1); } else{ return(0); } } int is_prime(int p){ int i; if(p < 2){ return(0); } i = 2; while(i*i <= p){ if(p % i == 0){ return 0; } i++; } return(1); } int find_primes(int max_num, int * buffer){ int buf_index = 0; int i; for(i = 2; i <= max_num; i++){ if(is_prime(i)){ pthread_mutex_lock(&mutex); buffer[buf_index] = i; buf_index++; pthread_mutex_unlock(&mutex); } } return(buf_index); } int main(int argc, char **argv){ if(argc < 3){ printf("usage: hw2a MAX_NUM MAX_THREADS\\n"); return(1); } unsigned int max_num = atoi(argv[1]); unsigned int num_threads = atoi(argv[2]); int * buffer = malloc(max_num*sizeof(int)); omp_set_num_threads(num_threads); int num_primes = find_primes(max_num,buffer); int i; if(num_primes > 0){ qsort(buffer,num_primes,sizeof(int),(int(*)(const void*,const void*))compare); printf("%d",buffer[0]); for(i = 1; i < num_primes; i++){ printf(", %d", buffer[i]); } printf("\\n"); } return(0); }
1
#include <pthread.h> void* produce(void *arg) { for (;;) { pthread_mutex_lock(&put.mutex); if (put.nput >= nitems) { pthread_mutex_unlock(&put.mutex); return 0; } buff[put.nput] = put.val; put.nput++; put.nval++; pthread_mutex_unlock(&put.mutex); pthread_mutex_lock(&nready.mutex); if (nready.nready == 0) { pthread_cond_signal(&nready.cond); } nready.nready++; pthread_mutex_unlock(&nready.mutex); *((int*)arg)+=1; } return 0; } void* consume(void* arg) { int i; for (i = 0; i < nitems; i++) { pthread_mutex_lock(&nready.mutex); while(nready.nready == 0) { pthread_cond_wait(&nready.cond, &nready.mutex); } nready.nready--; pthread_mutex_unlock(&nready.mutex); if (buff[i] != i) { printf("mutex error in %dth element!!!\\n", i); } } return 0; }
0
#include <pthread.h> void operand1_mutex(); void operand2_mutex(); pthread_mutex_t filemutex; int main(int argc, char *argv[]) { pthread_t t1; pthread_t t2; pthread_mutex_init(&filemutex, 0); printf("Operand mixer\\n"); printf("\\nStarting threads WITHOUT mutex\\n"); pthread_create( &t1, 0,(void*) &operand1_mutex, 0 ); pthread_create( &t2, 0,(void*) &operand2_mutex, 0 ); pthread_join( t1, 0 ); pthread_join( t2, 0 ); printf( "Completed threads t1 and t2\\n" ); return 0; } void operand1_mutex() { FILE *outfile; int i, rand1, rand2; if( ( outfile = fopen( "out_nomutex.log", "a" ) ) == 0 ) { printf( "\\nCannot open file\\n" ); exit( 1 ); } for( i = 0; i < 400; i++ ) { rand1 = rand(); rand2 = rand(); pthread_mutex_lock(&filemutex); fprintf( outfile, "t1 %d, ", rand1 ); fflush( outfile ); delay(5); fprintf( outfile, "t1 %d\\n", rand2 ); delay(55); pthread_mutex_unlock(&filemutex); fflush( outfile ); if( i % 40 == 0 ) printf( "." ); } fclose( outfile ); } void operand2_mutex() { FILE *outfile; int i, rand1, rand2; if( ( outfile = fopen( "out_nomutex.log", "a" ) ) == 0 ) { printf( "Cannot open file\\n" ); exit( 1 ); } for( i = 0; i < 400; i++ ) { rand1 = rand(); rand2 = rand(); pthread_mutex_lock(&filemutex); fprintf( outfile, "t2 %d, ", rand1 ); fflush( outfile ); delay( 5 ); fprintf( outfile, "t2 %d\\n", rand2 ); delay( 55 ); pthread_mutex_unlock(&filemutex); fflush( outfile ); } fclose( outfile ); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void *); void *thread2(void *); int i = 1; int main(void) { pthread_t t_a; pthread_t t_b; pthread_create(&t_a, 0, thread1, (void *)0); pthread_create(&t_b, 0, thread2, (void *)0); pthread_join(t_b, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(0); } void *thread1(void *junk) { for(i = 1; i <= 9; i++) { printf("thread1 get mutex lock...\\n"); pthread_mutex_lock(&mutex); printf("thread1 get mutex lock OK!\\n"); pthread_mutex_unlock(&mutex); printf("thread1 release mutex lock\\n"); usleep(50); } } void *thread2(void *junk) { while(i < 9) { printf("thread2 get mutex lock...\\n"); pthread_mutex_lock(&mutex); printf("thread2 get mutex lock OK!\\n"); pthread_cond_wait(&cond, &mutex); while(1) sleep(10); pthread_mutex_unlock(&mutex); printf("thread2 release mutex lock\\n"); usleep(50); } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int stage = 0; void *check_in_thread(void *load_area) { pthread_mutex_lock(&mutex); stage = 1; pthread_cond_signal(&cond); while (stage != 2) { pthread_cond_wait(&cond, &mutex); } assert(nacl_dyncode_delete(0, 0) == 0); stage = 3; pthread_cond_signal(&cond); while (stage != 4) { pthread_cond_wait(&cond, &mutex); } assert(nacl_dyncode_delete(load_area, NACL_BUNDLE_SIZE) == 0); pthread_mutex_unlock(&mutex); return 0; } void test_threaded_delete(void) { pthread_t other_thread; void *load_area = allocate_code_space(1); uint8_t buf[NACL_BUNDLE_SIZE]; int rc; fill_nops(buf, sizeof(buf)); assert(pthread_create(&other_thread, 0, check_in_thread, load_area) == 0); assert(nacl_dyncode_create(load_area, buf, sizeof(buf)) == 0); pthread_mutex_lock(&mutex); while (stage != 1) { pthread_cond_wait(&cond, &mutex); } rc = nacl_dyncode_delete(load_area, sizeof(buf)); assert(rc == -1); assert(errno == EAGAIN); stage = 2; pthread_cond_signal(&cond); while (stage != 3) { pthread_cond_wait(&cond, &mutex); } assert(nacl_dyncode_delete(load_area, sizeof(buf)) == 0); assert(nacl_dyncode_create(load_area, buf, sizeof(buf)) == 0); rc = nacl_dyncode_delete(load_area, sizeof(buf)); assert (rc == -1); assert (errno == EAGAIN); stage = 4; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); assert(pthread_join(other_thread, 0) == 0); }
1
#include <pthread.h> void *producer(),*consumer(); int *array; int limit=-1; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char **argv) { int howmany; pthread_t johntid,marytid; long long *howlong; howmany=atoi(argv[1]); array=calloc(howmany,sizeof(int)); pthread_create(&marytid,0, consumer, &howmany); pthread_create(&johntid,0, producer, &howmany); pthread_join(johntid,0); pthread_join(marytid,(void **)&howlong); printf("John and Mary Threads done with wait %lld\\n",*howlong); } void * producer(int *howmany) { int i; for (i=0;i<*howmany;i++) { array[i]=i; if (!i%1000) { pthread_mutex_lock(&mtx); limit=i; pthread_mutex_unlock(&mtx); } } pthread_mutex_lock(&mtx); limit=i-1; pthread_mutex_unlock(&mtx); printf("John produced %d Numbers\\n",*howmany); pthread_exit(0); } void *consumer(int *howmany) { int i,mylimit; long long sum=0; long long *wait; wait =malloc (sizeof (long long)); *wait=0; i=0; while (i< *howmany) { pthread_mutex_lock(&mtx); if (mylimit == limit) (*wait)++; mylimit=limit; pthread_mutex_unlock(&mtx); while (i<=mylimit) sum+=array[i++]; } printf("Mary consumed %d Numbers for a total of %lld\\n",*howmany,sum); pthread_exit(wait); }
0
#include <pthread.h> struct s { int datum; struct s *next; } *A, *B; void init (struct s *p, int x) { p -> datum = x; p -> next = 0; } pthread_mutex_t A_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B_mutex = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int *ip; struct s *t, *sp; struct s *p = malloc(sizeof(struct s)); init(p,7); pthread_mutex_lock(&B_mutex); t = A->next; A->next = sp; sp->next = t; pthread_mutex_unlock(&B_mutex); return 0; } int main () { pthread_t t1; int *ip; struct s *sp; struct s *p = malloc(sizeof(struct s)); init(p,9); A = malloc(sizeof(struct s)); init(A,3); A->next = p; B = malloc(sizeof(struct s)); init(B,5); pthread_create(&t1, 0, t_fun, 0); ip = &p->datum; sp = ((struct s *)((char *)(ip)-(unsigned long)(&((struct s *)0)->datum))); pthread_mutex_lock(&A_mutex); p = A->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&A_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t cmutex; int array_a[10], array_b[10], array_c[10]; int smallest_value, largest_value, average_value; void print_array(int array_x[10], char *name) { if (!1){ printf("%s: ", name); int i; for(i = 0; i < 10; i++){ printf("%d ", array_x[i]); } printf("\\n"); } } void *thread_worker(void *thread_id) { int i; long tid; tid = (long)thread_id; int chunk_size = 10 / 4; int start_index = tid * chunk_size; int end_index = (tid + 1) * chunk_size - 1; if (tid == 4 - 1) end_index = 10 - 1; if (!1) printf("Thread ID: %ld, start_index: %d, end_index: %d\\n", tid, start_index, end_index); for(i = start_index; i <= end_index; i++){ array_a[i] = rand() % 10; array_b[i] = rand() % 10; } for(i = start_index; i <= end_index; i++){ array_c[i] = (array_a[i] + array_b[i]) / 2; } int local_smallest_value = 10; int local_largest_value = -1; int local_sum_value = 0; for(i = start_index; i <= end_index; i++){ if (array_c[i] < local_smallest_value){ local_smallest_value = array_c[i]; } if (array_c[i] > local_largest_value){ local_largest_value = array_c[i]; } local_sum_value += array_c[i]; } pthread_mutex_lock(&cmutex); if (local_smallest_value < smallest_value) smallest_value = local_smallest_value; if (local_largest_value > largest_value) largest_value = local_largest_value; average_value += local_sum_value; pthread_mutex_unlock(&cmutex); pthread_exit(0); } int main() { smallest_value = 10; largest_value = -1; average_value = 0; srand(time(0) + 1); pthread_t threads[4]; int rc; long t; pthread_mutex_init(&cmutex, 0); for(t = 0; t < 4; t++){ rc = pthread_create(&threads[t], 0, thread_worker, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(1); } } for(t = 0; t < 4; t++){ rc = pthread_join(threads[t], 0); if (rc){ printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(1); } } pthread_mutex_destroy(&cmutex); print_array(array_a, "Array A"); print_array(array_b, "Array B"); print_array(array_c, "Array C"); average_value /= 10; printf("Smallest: %d, Largest: %d, Average: %d\\n", smallest_value, largest_value, average_value); pthread_exit(0); return 0; }
0
#include <pthread.h> int *item; } matrixIndex; int tid; double scalar; } thread_data_t; int NUM_THREADS; pthread_mutex_t valLock = PTHREAD_MUTEX_INITIALIZER; int* nextVal = 0; int valueReady = 0; pthread_cond_t checkSignal = PTHREAD_COND_INITIALIZER; pthread_mutex_t signalLock = PTHREAD_MUTEX_INITIALIZER; int valPickedUp = 0; void delay( int secs ) { secs += time(0); while (time(0) < secs); } void mathDelay( int value ) { int i,j; for(i = 0; i<value; i++) { for(j = 0; j < value; j++); } } void printMatrix(int** matrix, int width, int length) { int i, j; for(i = 0; i < length; i++) { for(j = 0; j < width; j++) { printf("%d ", matrix[i][j]); } printf("\\n"); } printf("-------------------------------------------------------\\n"); } void *scalarMultiply( void *arg ) { thread_data_t *data = (thread_data_t *)arg; while(1) { pthread_mutex_lock(&signalLock); if (!valueReady) { pthread_cond_wait(&checkSignal, &signalLock); } valueReady = 0; while (pthread_mutex_trylock(&valLock)) { if (!valueReady) { pthread_cond_wait(&checkSignal, &signalLock); } valueReady = 0; } pthread_mutex_unlock(&signalLock); valPickedUp = 1; *nextVal += data->tid; pthread_mutex_unlock(&valLock); mathDelay(1050); } } int scalarMultiply2d(int** matrix, int width, int length, double scalar) { int i, j, rc; pthread_t thr[NUM_THREADS]; thread_data_t thr_data[NUM_THREADS]; pthread_mutex_lock(&valLock); for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = 1 + i; thr_data[i].scalar = scalar; if ((rc = pthread_create(&thr[i], 0, scalarMultiply, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for(i = 0; i < length; i++) { for(j = 0; j < width; j++) { nextVal = &matrix[i][j]; pthread_mutex_unlock(&valLock); valueReady = 1; pthread_cond_signal(&checkSignal); while(!valPickedUp); valPickedUp = 0; pthread_mutex_lock(&valLock); } } for (i = 0; i < NUM_THREADS; i++) { pthread_cancel(thr[i]); } } int main(int argc, char **argv) { int **matrix; int width = 30; int length = 30; int i, j; NUM_THREADS = 4; if (argc >= 3) { width = atoi(argv[1]); length = atoi(argv[2]); } if (argc >= 4) { NUM_THREADS = atoi(argv[3]); } matrix = malloc(sizeof(int**) * length); for(i = 0; i < length; i++) { matrix[i] = malloc(sizeof(int*) * width); for(j = 0; j < width; j++) { matrix[i][j] = 0; } } printMatrix(matrix, width, length); scalarMultiply2d(matrix, width, length, 3); printMatrix(matrix, width, length); for(i = 0; i < length; i++) { free(matrix[i]); } free(matrix); }
1
#include <pthread.h> int n, thread_count, flag; double sum, w; pthread_mutex_t mutex; void* thread_sum(void *rank) { int *ranki = (int *) rank; int start = *ranki*n/thread_count; int end = (*ranki+1)*n/thread_count; double local_sum = 0.0, x; int i; w=(double)1.0/(double)n; for (i=start; i<end; i++){ x = w*((double)i-0.5); local_sum += (4.0/(1.0+x*x)); } pthread_mutex_lock(&mutex); sum += local_sum; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char* argv[]) { int i; double pi; thread_count = strtol(argv[1], 0, 10); n = strtol(argv[2], 0, 10); if (n % thread_count != 0){ printf("n has to be a multiple of the number of threads\\n"); return 0; } pthread_t* thread_handles; int *threads; threads = (int *)malloc(thread_count*sizeof(int)); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); sum = 0.0; flag = 0; for (i = 0; i < thread_count; i++){ threads[i] = i; pthread_create(&thread_handles[i], 0, thread_sum, (void*)&threads[i]); } for (i = 0; i < thread_count; i++){ pthread_join(thread_handles[i], 0); } pi = w*sum; printf("pi = %f \\n", pi); free(threads); free(thread_handles); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* start_thread() { int *n, fd, c; ssize_t size; n = (int *)malloc(sizeof(int)); *n = 0; for (c = 0; c != 100; c++) { pthread_mutex_lock(&mutex); fd = open("Example.txt", O_RDWR, 0600); if (fd == -1) { do {perror("open thread"); exit(1); } while(0); } size = pread(fd, n, sizeof(int), 0); if ((size_t)size < sizeof(int)) { do {perror("pread thread"); exit(1); } while(0); } (*n)++; size = pwrite(fd, n, sizeof(int), 0); close(fd); pthread_mutex_unlock(&mutex); if ((size_t)size < sizeof(int)) { do {perror("pwrite thread"); exit(1); } while(0); } } free(n); sleep(1); pthread_exit(0); } int main() { int s, c, ans, fd; void *res; pthread_t id_arr[10]; fd = open("Example.txt", O_RDWR | O_CREAT | O_TRUNC, 0600); if (fd == -1) { do {perror("open main\\n"); exit(1); } while(0); } ans = 0; s = pwrite(fd, &ans, sizeof(int), 0); if (s == -1) { do {perror("write main\\n"); exit(1); } while(0); } for (c = 0; c != 10; c++) { s = pthread_create(&id_arr[c], 0, start_thread, 0); if (s != 0) do { errno = s; perror("pthread_create\\n"); exit(1); } while (0); } for (c = 0; c!= 10; c++) { s = pthread_join(id_arr[c], &res); if (s != 0) do { errno = s; perror("pthread_join\\n"); exit(1); } while (0); free(res); } sleep(1); s = pread(fd, &ans, sizeof(int), 0); if (s == -1) { do {perror("read main\\n"); exit(1); } while(0); } printf("%d\\n", ans); pthread_mutex_destroy(&mutex); close(fd); sleep(1); exit(0); }
1
#include <pthread.h> int queue[100]; int length; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER; void *producer_thread(void *); void *consumer_thread(void *); void print_queue(); int main(int argc, char *argv[]) { srand(time(0)); int NUM_PROD, NUM_CONS; NUM_PROD = atoi(argv[1]); NUM_CONS = atoi(argv[1]); pthread_t *ptid, *ctid; ptid = (pthread_t *)calloc(NUM_PROD, sizeof(pthread_t)); ctid = (pthread_t *)calloc(NUM_CONS, sizeof(pthread_t)); int i; for (i = 0; i < NUM_PROD; i++) { if (pthread_create(&(ptid[i]), 0, &producer_thread, 0) != 0) { perror("pthread_create producer"); exit(-1); } } for (i = 0; i < NUM_CONS; i++) { if (pthread_create(&(ctid[i]), 0, &consumer_thread, 0) != 0) { perror("pthread_create consumer"); exit(-1); } } for (i = 0; i < NUM_PROD; i++) { if (pthread_join(ptid[i], 0) != 0) { perror("pthread_join producer"); kill(getpid(), SIGINT); } } for (i = 0; i < NUM_CONS; i++) { if (pthread_join(ctid[i], 0) != 0) { perror("pthread_join consumer"); kill(getpid(), SIGINT); } } return 0; } int enqueue(int * queue, int value, pthread_mutex_t *m) { if (length == 100) { pthread_cond_wait(&cond_producer, m); } queue[length] = value; length++; pthread_cond_signal(&cond_consumer); return 0; } int dequeue(int *queue, pthread_mutex_t *m) { if (length == 0) { pthread_cond_wait(&cond_consumer, m); } length--; int value; value = queue[length]; pthread_cond_signal(&cond_producer); return value; } void *producer_thread(void *pointer) { pthread_mutex_lock(&mutex); int value; value = rand() % 100; printf("produce %d ", value); print_queue(); enqueue(queue, value, &mutex); pthread_mutex_unlock(&mutex); pthread_exit((void *) 0); } void *consumer_thread(void *pointer) { pthread_mutex_unlock(&mutex); int value; value = dequeue(queue, &mutex); printf("consume %d\\n", value); print_queue(); pthread_mutex_unlock(&mutex); pthread_exit((void *) 0); } void print_queue() { int i = 0; for (i = 0; i < length; i++) { printf("%d ", queue[i]); } printf("\\n"); }
0
#include <pthread.h> long unsigned int seconds1 ; long unsigned int seconds2; char message1[50]; { pthread_cond_t cond; int seconds; char message[50]; struct tag *next; }my_struct; struct mutex { pthread_mutex_t mutex; pthread_cond_t cond1; pthread_cond_t cond2; my_struct *head ; }mutex={.mutex = PTHREAD_MUTEX_INITIALIZER,.cond1 = PTHREAD_COND_INITIALIZER,.cond2=PTHREAD_COND_INITIALIZER}; void insert(my_struct *temp) { my_struct *current = 0; my_struct *prev = 0; int count = 0; static int flag = 0; current = mutex.head; if(mutex.head == 0) { if((flag == 1) && (temp->seconds < (seconds1))){ mutex.head = (my_struct *)temp; temp->next = 0; pthread_cond_signal(&mutex.cond2); } else { mutex.head = (my_struct *)temp; temp->next = 0; pthread_cond_signal(&mutex.cond1); flag =1; } } else { while(current -> next != 0 && temp -> seconds > current -> seconds ) { count++; prev = current; current = current->next; } if( current -> next == 0 && temp->seconds > current->seconds) { current->next = temp; temp->next = 0; } else if( count == 0) { if(current != 0 && temp->seconds <= current->seconds) { temp->next = current; mutex.head = temp; pthread_cond_signal(&mutex.cond2); } else { mutex.head = temp; temp->next = 0; pthread_cond_signal(&mutex.cond2); } } else { current = prev; temp -> next = current -> next; current -> next = temp; } } } void delete( ) { my_struct *current = 0; current = (my_struct *)mutex.head; seconds1 = current -> seconds; strcpy(message1,current->message); mutex.head = (my_struct *)current->next; free(current); } void *fun(void *p) { int status; struct timespec time1; while(1){ pthread_mutex_lock(&mutex.mutex); if(mutex.head == 0) { pthread_cond_wait(&mutex.cond1,&mutex.mutex); } delete(); seconds2 = seconds1 - time(0); time1.tv_sec = seconds1; if(pthread_cond_timedwait(&mutex.cond2,&mutex.mutex,&(time1)) == 110) { printf("(%lu) %s\\n",(seconds2),message1); pthread_mutex_unlock(&mutex.mutex); } else { my_struct *back =(my_struct *) malloc(sizeof(my_struct)); back->seconds = seconds1; strcpy(back->message , message1); insert(back); pthread_mutex_unlock(&mutex.mutex); } } } int main() { my_struct *alarm; unsigned int seconds; int status; char line[120]; char message[64]; int pid; pthread_t thread; status = pthread_create(&thread,0,fun,0); while(1){ printf("Alarm:"); if(status != 0) { printf("pthread_create failed"); } if(fgets(line, sizeof(line), stdin) == 0) exit(0); if(strlen(line) <= 1){ free(alarm); continue; } alarm = (my_struct *)malloc(sizeof(my_struct)); if(sscanf(line,"%d %64[^\\n]",&seconds,message)<2) { fprintf(stderr,"Bad command\\n"); free(alarm);alarm = 0; printf("line"); continue; } alarm->seconds = time(0) + seconds; strcpy(alarm->message,message); pthread_mutex_lock(&mutex.mutex); insert(alarm); pthread_mutex_unlock(&mutex.mutex); } pthread_exit(0); }
1
#include <pthread.h> int buf[10]; pthread_mutex_t lock; void* producer(void* param) { int i; pthread_mutex_lock(&lock); for (i = 0; i < 10; ++i) { buf[i] = i; } pthread_mutex_unlock(&lock); pthread_exit(0); } void* consumer(void* param) { int i; pthread_mutex_lock(&lock); for (i = 0; i < 10; ++i) { printf("Buffer Index %d = %d\\n", i, buf[i]); } pthread_mutex_unlock(&lock); pthread_exit(0); } int main(int argc, const char * argv[]) { pthread_t t_prod, t_cons; pthread_mutex_init(&lock, 0); pthread_create(&t_prod, 0, producer, 0); sleep(1); pthread_create(&t_cons, 0, consumer, 0); pthread_join(t_prod, 0); pthread_join(t_cons, 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> int numOfBottles=25; int guestInfo[20][3]; int moodOfHost = 0; int i; pthread_mutex_t refr; pthread_t guestsArray[20]; pthread_t host; void *guestFunc(void *arg){ srand(time(0)); int posNumber = *((int *) arg); while(1){ pthread_mutex_lock(&refr); guestInfo[posNumber][0] = 1; napms(4000); numOfBottles--; if(moodOfHost==0) pthread_mutex_unlock(&refr); guestInfo[posNumber][0] = 2; napms(30000); guestInfo[posNumber][1]++; guestInfo[posNumber][0] = 0; if(guestInfo[posNumber][1] >= guestInfo[posNumber][2]){ guestInfo[posNumber][0] = 3; napms(40000); } } } void *hostFunc(){ pthread_mutex_init(&refr, 0); srand(time(0)); while(1){ if(rand()%15 == 1){ moodOfHost=1; pthread_mutex_init(&refr, 0); pthread_mutex_lock(&refr); if(numOfBottles < 10){ moodOfHost = 2; numOfBottles+=10; } napms(2000); pthread_mutex_unlock(&refr); moodOfHost=0; } if(rand()%140 == 5){ moodOfHost = 2; } napms(1000); } } void printGuestCondition(int pos){ switch(guestInfo[pos][0]){ case 0: printw(" in queue "); break; case 1: printw(" taking a beer "); break; case 2: printw(" drinking "); break; case 3: printw(" sleeping "); break; } } printHostActivity(){ switch(moodOfHost){ case 0: printw(" watching tv \\n"); break; case 1: printw(" checking a fridge \\n"); break; case 2: printw(" adding some bottles \\n"); break; case 3: printw(" tired \\n"); break; } } int main() { srand(time(0)); initscr(); printw("\\n"); pthread_create(&host, 0, hostFunc, 0); for(i = 0; i < 20; i++){ int *arg = malloc(sizeof(*arg)); *arg = i; pthread_create(&guestsArray[i], 0, guestFunc, arg); guestInfo[i][0] = 0; guestInfo[i][1] = 0; guestInfo[i][2] = rand()%8+3; } printw(" Teh party has started!1 \\n"); while(1){ printw(" Now host is "); printHostActivity(); if(numOfBottles > 0){ if(numOfBottles != 1) printw(" There are %d bottles \\n",numOfBottles); else printf(" There is one bottle \\n"); }else if(numOfBottles <= 0 || moodOfHost == 3){ printw(" There are no bottles in the fridge\\n"); printw(" The party is over \\n"); refresh(); napms(10000); endwin(); break; } for(i = 0; i < 20; i++){ printw(" %d",i); printGuestCondition(i); printw(" %d %d \\n",guestInfo[i][1],guestInfo[i][2]); } if(moodOfHost == 3){ printw("Host added 3 bottles in the fridge \\n");} refresh(); napms(2000); clear(); } endwin(); }
1
#include <pthread.h> int memory[(2*32+1)]; int next_alloc_idx = 1; pthread_mutex_t m; int top; int index_malloc(){ int curr_alloc_idx = -1; pthread_mutex_lock(&m); if(next_alloc_idx+2-1 > (2*32+1)){ pthread_mutex_unlock(&m); curr_alloc_idx = 0; }else{ curr_alloc_idx = next_alloc_idx; next_alloc_idx += 2; pthread_mutex_unlock(&m); } return curr_alloc_idx; } void EBStack_init(){ top = 0; } int isEmpty() { if(top == 0) return 1; else return 0; } int push(int d) { int oldTop = -1, newTop = -1, casret = -1; newTop = index_malloc(); if(newTop == 0){ return 0; }else{ memory[newTop+0] = d; while (1) { oldTop = top; memory[newTop+1] = oldTop; if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){ return 1; } } } } void __VERIFIER_atomic_assert(int r) { __atomic_begin(); assert(!(!r || !isEmpty())); __atomic_end(); } void push_loop(){ int r = -1; int arg = __nondet_int(); while(1){ r = push(arg); __VERIFIER_atomic_assert(r); } } pthread_mutex_t m2; int state = 0; void* thr1(void* arg) { pthread_mutex_lock(&m2); switch(state) { case 0: EBStack_init(); state = 1; case 1: pthread_mutex_unlock(&m2); push_loop(); break; } return 0; } int main() { pthread_t t1,t2; pthread_create(&t1, 0, thr1, 0); pthread_create(&t2, 0, thr1, 0); return 0; }
0
#include <pthread.h> int data; struct _node * left; struct _node * right; } node; void * tmain(void *); void do_work(void); void init_mutexes(void); void init_workers(int param[]); void wind_up(void); void process_node(node * n, int sorted[], int * i); void tree_insert(node ** t, int k, int * count); void tree_in_order_walk(node * t, int sorted[], int * i); pthread_mutex_t mem_mutex; pthread_t tid[2]; int * sorted[2]; int count[2]; int main(void) { int i, param[2]; for (i = 0; i < 2; i++) { param[i] = i; } init_mem(); init_mutexes(); init_workers(param); do_work(); wind_up(); return 0; } void * tmain(void * tno) { int i = * (int *) tno, num, n = 0; char * file_name_format = "input%d.txt", file_name[11]; FILE * fp; node * tree = 0; sprintf(file_name, file_name_format, i + 1); fp = fopen(file_name, "r"); count[i] = 0; while (fscanf(fp, "%d", &num) != EOF) { tree_insert(&tree, num, &count[i]); } fclose(fp); sorted[i] = mem_malloc(count[i] * sizeof(int)); tree_in_order_walk(tree, sorted[i], &n); pthread_exit(0); } void do_work(void) { int i, * p1, * p2, prev, flag = 0; FILE * fp; for (i = 0; i < 2; i++) { if (pthread_join(tid[i], 0)) fprintf(stderr, "Master: Unable to wait for worker %d\\n", i); else printf("Master: Worker %d has exited\\n", i); } printf("array 1: "); for (i = 0; i < count[0]; i++) { printf("%d ", sorted[0][i]); } printf("\\n"); printf("array 2: "); for (i = 0; i < count[1]; i++) { printf("%d ", sorted[1][i]); } printf("\\n"); printf("Merging...\\n"); fp = fopen("output.txt", "w"); p1 = sorted[0]; p2 = sorted[1]; while (count[0] > 0 && count[1] > 0) { if (*p1 < *p2) { if (*p1 == prev && flag) { p1++; count[0]--; continue; } fprintf(fp, "%d\\n", *p1); flag = 1; prev = *p1; p1++; count[0]--; } else if (*p1 > *p2) { if (*p2 == prev && flag) { p2++; count[1]--; continue; } fprintf(fp, "%d\\n", *p2); flag = 1; prev = *p2; p2++; count[1]--; } else { p1++; count[0]--; continue; } } flag = 0; while (count[0] > 0) { if (*p1 == prev && flag) { p1++; count[0]--; } fprintf(fp, "%d\\n", *p1); flag = 1; prev = *p1; p1++; count[0]--; } while (count[1] > 0) { if (*p2 == prev && flag) { p2++; count[1]--; } fprintf(fp, "%d\\n", *p2); flag = 1; prev = *p2; p2++; count[1]--; } fclose(fp); mem_free(sorted[0]); mem_free(sorted[1]); } void init_mutexes(void) { pthread_mutex_init(&mem_mutex, 0); pthread_mutex_trylock(&mem_mutex); pthread_mutex_unlock(&mem_mutex); } void init_workers(int param[]) { int i; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 2; i++) { param[i] = i; if (pthread_create(&tid[i], &attr, tmain, (void *) &param[i])) { fprintf(stderr, "Master: Unable to create worker %d. Exiting...\\n", param[i]); pthread_attr_destroy(&attr); exit(1); } printf("Master: Worker %d created\\n", param[i]); } pthread_attr_destroy(&attr); } void wind_up(void) { printf("Winding up...\\n"); pthread_mutex_destroy(&mem_mutex); } void process_node(node * n, int sorted[], int * i) { if (! n) return; sorted[*i] = n->data; (*i) = (*i) + 1; } void tree_insert(node ** t, int k, int * count) { if((*t) == 0) { pthread_mutex_lock(&mem_mutex); (*t) = mem_malloc(sizeof(node)); pthread_mutex_unlock(&mem_mutex); (*t)->left = 0; (*t)->right = 0; (*t)->data = k; (*count) = (*count) + 1; } else if((*t)->data >= k) { tree_insert(&((*t)->left), k, count); } else { tree_insert(&((*t)->right), k, count); } } void tree_in_order_walk(node * t, int sorted[], int * i) { if (t == 0) return; tree_in_order_walk(t->left, sorted, i); process_node(t, sorted, i); tree_in_order_walk(t->right, sorted, i); pthread_mutex_lock(&mem_mutex); mem_free(t); pthread_mutex_unlock(&mem_mutex); }
1
#include <pthread.h> static int glob = 0; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static void *thread_routine(void *arg) { int loc, j; for (j = 0; j < 10000000; j++) { pthread_mutex_lock(&mtx); loc = glob; loc++; glob = loc; pthread_mutex_unlock(&mtx); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int s; s = pthread_create(&t1, 0, thread_routine, 0); if (s != 0) do { errno = s; perror("pthread_create"); exit(1); } while (0); s = pthread_create(&t2, 0, thread_routine, 0); if (s != 0) do { errno = s; perror("pthread_create"); exit(1); } while (0); s = pthread_join(t1, 0); if (s != 0) do { errno = s; perror("pthread_join"); exit(1); } while (0); s = pthread_join(t2, 0); if (s != 0) do { errno = s; perror("pthread_join"); exit(1); } while (0); printf("glob = %d\\n", glob); exit(0); }
0
#include <pthread.h> void vpn_loop(struct options opt) { struct Ctunnel **ctunnel; struct Network *net_srv = 0; char dev[5] = ""; int i = 0, x = 0, srv_sockfd = 0, ret = 0, tunfd = 0; int pool = 1; pthread_t tid[MAX_THREADS]; extern int threads[MAX_THREADS]; crypto_init = gcrypt_crypto_init; crypto_deinit = gcrypt_crypto_deinit; pthread_mutex_init(&mutex, 0); for (i = 0; i < MAX_THREADS; i++) threads[i] = 0; for (i = 0; i < MAX_THREADS; i++) tid[i] = (pthread_t) 0; for (i = 0; i < MAX_CLIENTS; i++) { memset(hosts[i].natip, 0x00, sizeof(hosts[i].natip)); memset(hosts[i].tunip, 0x00, sizeof(hosts[i].tunip)); hosts[i].time = (time_t) 0; hosts[i].id = 0; } i = 0; ctunnel = malloc(sizeof(struct Ctunnel **) * MAX_THREADS); if (!ctunnel) { fprintf(stderr, "MALLOC %s\\n", strerror(errno)); exit(1); } if (opt.role == SERVER) { sprintf(opt.gw, "%s.%d", opt.pool, pool); if (opt.vmode == VMODE_TUN) { sprintf(dev, "tun%d", opt.tun); if ((tunfd = mktun(dev)) < 0) { fprintf(stderr, "mktun: %s\\n", strerror(errno)); exit(1); } ifconfig(dev, opt.gw, opt.gw, "255.255.255.0"); } else { sprintf(dev, "ppp%d", opt.tun); } ctunnel_log(stdout, LOG_INFO, "PtP Pool Local Address %s", opt.gw); } if (opt.proto == TCP) { if (opt.role == SERVER) srv_sockfd = tcp_listen(opt.local.ip, opt.local.ps); net_srv = calloc(1, sizeof(struct Network)); } if (srv_sockfd < 0) { ctunnel_log(stderr, LOG_CRIT, "listen() %s\\n", strerror(errno)); exit(1); } i = 0; if (opt.role == SERVER) { while (1) { if (opt.proto == TCP) net_srv->sockfd = tcp_accept(srv_sockfd); else net_srv = udp_bind(opt.local.ip, opt.local.ps, 0); i = clients = 0; if (net_srv->sockfd > 0) { pthread_mutex_lock(&mutex); for (i = 0; i != MAX_THREADS; i++) { if (threads[i] == 0) break; if (i == MAX_THREADS) ctunnel_log(stderr, LOG_CRIT, "Max Threads %d " "reached!", i); } ctunnel[i] = malloc(sizeof(struct Ctunnel)); ctunnel[i]->net_srv = net_srv; ctunnel[i]->srvsockfd = net_srv->sockfd; ctunnel[i]->tunfd = tunfd; ctunnel[i]->opt = opt; ctunnel[i]->id = i; ctunnel[i]->srv_sockfd = srv_sockfd; ctunnel[i]->ectx = 0; ctunnel[i]->dctx = 0; ctunnel[i]->ectx = crypto_init(opt, 1); ctunnel[i]->dctx = crypto_init(opt, 0); pthread_mutex_unlock(&mutex); threads[i] = 2; if (ctunnel[i]->opt.vmode == VMODE_PPP) ctunnel[i]->tunfd = prun(ctunnel[i]->opt.ppp); if (opt.proto == UDP) { ctunnel_log(stdout, LOG_INFO, "UDP Waiting"); vpn_thread(ctunnel[i]); } else { ret = pthread_create(&tid[i], 0, (void *) vpn_thread, (void *) ctunnel[i]); if (ret != 0) fprintf(stderr, "Cannot create thread\\n"); for (x = 0; x != MAX_THREADS; x++) { if (threads[x] == 2) { fprintf(stdout, "Joining thread %d\\n", x); pthread_join(tid[x], 0); pthread_mutex_lock(&mutex); threads[x] = 0; pthread_mutex_unlock(&mutex); free(ctunnel[x]); } } } } else { net_close(net_srv); } } } else { ctunnel[i] = malloc(sizeof(struct Ctunnel)); ctunnel[i]->opt = opt; ctunnel[i]->srv_sockfd = srv_sockfd; ctunnel[i]->id = i; ctunnel[i]->ectx = crypto_init(opt, 1); ctunnel[i]->dctx = crypto_init(opt, 0); ctunnel[i]->nets_t = 0; if (opt.proto == TCP) { net_srv->sockfd = tcp_connect(opt.remote.ip, opt.remote.ps); ctunnel[i]->net_srv = net_srv; } else { ctunnel[i]->net_srv = udp_connect(opt.remote.ip, opt.remote.ps, 5); } if (ctunnel[i]->opt.vmode == VMODE_PPP) ctunnel[i]->tunfd = prun(ctunnel[i]->opt.ppp); sprintf(dev, "tun%d", ctunnel[i]->opt.tun); if (opt.vmode == VMODE_TUN) { if ((ctunnel[i]->tunfd = mktun(dev)) < 0) { ctunnel_log(stderr, LOG_CRIT, "Unable to create TUN device, aborting!"); exit(1); } } if ((vpn_handshake(ctunnel[i])) < 0) { ctunnel_log(stderr, LOG_CRIT, "Handshake Error"); crypto_deinit(ctunnel[i]->ectx); crypto_deinit(ctunnel[i]->dctx); free(ctunnel[i]); free(ctunnel); exit(1); } vpn_thread(ctunnel[i]); } }
1
#include <pthread.h> char buffer[2000000]; int countarray[128]; pthread_mutex_t mutex; int buffstart, buffend; } argue, *argues; int ascicount(void *ar); int main(int argc, char *argv[]){ int *openfile, readcount, threadbyte, n; argue *datapass; pthread_t handlethreads[8]; pthread_attr_t thread; readcount = 0; if(access(argv[1], F_OK) == 0) { openfile = open(argv[1], O_RDONLY); } else{ printf("Source file does not exist.\\n"); return 1; } readcount = read(openfile, &buffer, 2000000); threadbyte = readcount/8; n = pthread_attr_init(&thread); if(n !=0){ printf("an error occurred\\n"); return 1; } datapass = calloc(8, sizeof(argue)); if(datapass == 0){ printf("error with calloc\\n"); } pthread_mutex_init(&mutex, 0); for(int i =0; i< 8; i++){ datapass[i]. buffstart = i * threadbyte; if(i==8 -1){ datapass[i]. buffend = (i * threadbyte) + threadbyte + 8; } else { datapass[i]. buffend = (i * threadbyte) + threadbyte; } pthread_create(&handlethreads[i], &thread, &ascicount, &datapass[i]); } for(int i =0; i<8; i++){ pthread_join(handlethreads[i], 0); } for(int i = 0; i<128;i++){ if(i<33 || i>126){ printf("%d occurences of 0x%x\\n", countarray[i], i); } else { printf("%d occurences of %c\\n", countarray[i], i); } } pthread_mutex_destroy(&mutex); pthread_exit(0); } int ascicount(void *ar){ argue *a = ar; for(int i= a->buffstart; i< (a->buffend);i++){ pthread_mutex_lock(&mutex); countarray[buffer[i]]++; pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int queue[1000000]; int queueStart = 0; int queueEnd = 0; int n = 50; int thSync = 1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static void *producer(void *arg); static void *consumer(void *arg); int main(int argc, char *argv[]) { if(argc > 1) { if(!strcmp(argv[1], "-nosync")) { thSync = 0; } else if(!strcmp(argv[1], "-sync")) { thSync = 1; } } if(argc > 2) { n = atoi(argv[2]); } pthread_t producerTh[10]; pthread_t consumerTh; void *pRes[10]; void *cRes; struct timeval t; gettimeofday(&t, 0); double tstart = t.tv_sec+(t.tv_usec/1000000.0); int i; for(i = 0; i < 10; i++) { if(pthread_create(&producerTh[i], 0, producer, "")) { printf("Error when creating producer thread %d\\n", i); return 1; } } if(pthread_create(&consumerTh, 0, consumer, "")) { printf("Error when creating costumer thread\\n"); return 1; } for(i = 0; i < 10; i++) { if(pthread_join(producerTh[i], &pRes[i])) { printf("Error when joining producer thread %d\\n", i); return 1; } } gettimeofday(&t, 0); double tend = t.tv_sec+(t.tv_usec/1000000.0); printf("Time: : %.6lf\\n", tend-tstart); printf("Produced: %d\\nConsumed: %d\\n", queueEnd, queueStart); return 0; } static void *producer(void *arg) { int i; for(i = 0; i < n; i++) { int item = arc4random(); if(thSync){ pthread_mutex_lock(&mutex); } queue[queueEnd] = item; queueEnd++; if(thSync){ pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } } return 0; } static void *consumer(void *arg) { int item; for(;;) { if(thSync){ pthread_mutex_lock(&mutex); if(queueEnd == queueStart) { pthread_cond_wait(&cond, &mutex); } } else { while(queueEnd == queueStart); } item = queue[queueStart]; queueStart++; if(thSync){ pthread_mutex_unlock(&mutex); } } return 0; }
1
#include <pthread.h> int global_i = 1; int global_j = 10; pthread_mutex_t mutex; pthread_mutex_t fict; pthread_cond_t blocked; void *ThreadsUseIt(void* num) { int i; long t; t = (long) num; pthread_mutex_lock(&mutex); i = global_i; global_i++; pthread_mutex_unlock(&mutex); printf("I`m thread %ld, I`m sleeping for %d second \\n", t, i); sleep(i); printf("Thread %ld woke up\\n", t); pthread_mutex_lock(&fict); global_j --; if (!global_j) pthread_cond_broadcast(&blocked); else { printf("Thread %ld wait\\n", t); pthread_cond_wait(&blocked, &fict); } printf("Thread %ld perfomed all works\\n", t); pthread_mutex_unlock(&fict); pthread_exit(0); } int main (int argc, char *argv[]) { int i; long t = 1; pthread_t threads[10]; pthread_attr_t attr; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&fict, 0); pthread_cond_init (&blocked, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 10; ++i) { pthread_create(&threads[i], &attr, ThreadsUseIt, (void *) t); printf("Thread %ld started\\n", t); ++t; } for (i = 0; i < 10; ++i) pthread_join(threads[i], 0); printf("All threads finished\\n"); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&fict); pthread_cond_destroy(&blocked); pthread_exit(0); }
0
#include <pthread.h> int still_tasks_left = 1; int pw_found = 0; char * current_task = 0; char * current_username = 0; char * current_solution = 0; char * current_pw = 0; char * pw_with_a = 0; size_t workload_per_thread = 0; size_t thread_c; int num_unknowns; int prefix_length; char * pw = 0; long total_count = 0; double start_time; double end_time; double CPU_start; double CPU_end; int result = 1; pthread_barrier_t myBarrier; pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER; char * replace_period_with_a(char * str) { char * tmp = strdup(str); size_t i = 0; for (; i < strlen(tmp); i++) { if (tmp[i] == '.') tmp[i] = 'a'; } return tmp; } int get_and_init_next_task() { char buffer[100]; if (fgets(buffer, 100, stdin)) { if (buffer[strlen(buffer) - 1] == '\\n') buffer[strlen(buffer) - 1] = '\\0'; free(current_task); free(pw_with_a); char * saveptr = 0; current_task = strdup(buffer); current_username = strtok_r(current_task, " ", &saveptr); current_solution = strtok_r(0, " ", &saveptr); current_pw = strtok_r(0, " ", &saveptr); num_unknowns = (int)(strlen(current_pw) - getPrefixLength(current_pw)); prefix_length = getPrefixLength(current_pw); pw_with_a = replace_period_with_a(current_pw); return 1; } free(current_task); free(pw_with_a); return 0; } void * crack(void * _index) { size_t index = (size_t)_index; long start_index; long count; char * starting_string = 0; double total_time; double total_CPU_time; while (still_tasks_left) { getSubrange(num_unknowns, thread_c, index, &start_index, &count); starting_string = strdup(pw_with_a); setStringPosition(starting_string + prefix_length, start_index); int status = 2; int hash_count = 0; char * hash = 0; struct crypt_data cdata; cdata.initialized = 0; if (index == 1) { start_time = getTime(); CPU_start = getCPUTime(); v2_print_start_user(current_username); } pthread_barrier_wait(&myBarrier); v2_print_thread_start(index, current_username, start_index, starting_string); int i = 0; for (; i < count; i++) { if (pw_found) { status = 1; break; } hash = crypt_r(starting_string, "xx", &cdata); hash_count++; if (strcmp(hash, current_solution) == 0) { pw_found = 1; status = 0; pw = strdup(starting_string); result = 0; break; } incrementString(starting_string + prefix_length); } free(starting_string); pthread_barrier_wait(&myBarrier); pw_found = 0; v2_print_thread_result(index, hash_count, status); pthread_mutex_lock(&myMutex); total_count += hash_count; pthread_mutex_unlock(&myMutex); pthread_barrier_wait(&myBarrier); if (index == 1) { end_time = getTime(); CPU_end = getCPUTime(); total_time = end_time - start_time; total_CPU_time = CPU_end - CPU_start; v2_print_summary(current_username, pw, total_count, total_time, total_CPU_time, result); free(pw); pw = 0; result = 1; total_count = 0; if (!get_and_init_next_task()) { still_tasks_left = 0; } } pthread_barrier_wait(&myBarrier); } return 0; } int start(size_t thread_count) { thread_c = thread_count; pthread_barrier_init(&myBarrier, 0, thread_count); pthread_t threads[thread_count]; get_and_init_next_task(); size_t i = 0; for (; i < thread_count; i++) { pthread_create(threads + i, 0, crack, (void*)(i + 1)); } size_t j = 0; for (; j < thread_count; j++) { pthread_join(threads[j], 0); } return 0; }
1
#include <pthread.h> struct MsgQueue* MsgQueueCreate(int id, int len, int width) { int i; struct MsgQueue* mq; mq = (struct MsgQueue*) malloc(sizeof(struct MsgQueue)); mq->m_id = id; mq->m_len = len; mq->m_width = width; mq->m_write_index = 0; mq->m_read_index = 0; mq->m_is_empty = CD_TRUE; mq->m_pp_data = (void **) malloc(sizeof(void *) * mq->m_len); for (i=0; i < mq->m_len; i++) { mq->m_pp_data[i] = (void*) malloc(mq->m_width); } pthread_cond_init(&mq->m_put_cond, 0); pthread_cond_init(&mq->m_get_cond, 0); pthread_mutex_init(&mq->m_mutex, 0); return mq; } int MsgQueueDelete(struct MsgQueue* mq) { int i; for (i=0; i < mq->m_len; i++) { free(mq->m_pp_data[i]); } free(mq->m_pp_data); free(mq); pthread_cond_destroy(&mq->m_put_cond); pthread_cond_destroy(&mq->m_get_cond); pthread_mutex_destroy(&mq->m_mutex); return CD_SUCCESS; } int MsgQueuePut(struct MsgQueue* mq, void * p_data) { pthread_mutex_lock(&mq->m_mutex); if( mq->m_is_empty ) { strncpy(mq->m_pp_data[mq->m_write_index], p_data, mq->m_width); mq->m_write_index = (mq->m_write_index+1) % mq->m_len; mq->m_is_empty = CD_FALSE; pthread_cond_signal(&mq->m_get_cond); } else { if( mq->m_write_index == mq->m_read_index ) { pthread_cond_wait(&mq->m_put_cond, &mq->m_mutex); if( !mq->m_is_empty && (mq->m_write_index==mq->m_read_index) ) { printf("ERROR: MsgQueue(id:%d) put error\\n", mq->m_id); pthread_mutex_unlock(&mq->m_mutex); return CD_ERROR; } } strncpy(mq->m_pp_data[mq->m_write_index], p_data, mq->m_width); mq->m_write_index = (mq->m_write_index+1) % mq->m_len; mq->m_is_empty = CD_FALSE; } pthread_mutex_unlock(&mq->m_mutex); return CD_SUCCESS; } void * MsgQueueGet(struct MsgQueue* mq, void* p_data) { pthread_mutex_lock(&mq->m_mutex); if( mq->m_is_empty ) { pthread_cond_wait(&mq->m_get_cond, &mq->m_mutex); if( mq->m_is_empty ) { printf("ERROR: MsgQueue(id:%d) get error\\n", mq->m_id); pthread_mutex_unlock(&mq->m_mutex); return 0; } } strncpy(p_data, mq->m_pp_data[mq->m_read_index], mq->m_width); mq->m_read_index = (mq->m_read_index+1) % mq->m_len; if( mq->m_write_index == mq->m_read_index ) mq->m_is_empty = CD_TRUE; pthread_cond_signal(&mq->m_put_cond); pthread_mutex_unlock(&mq->m_mutex); return p_data; } int MsgQueueIsFull(struct MsgQueue* mq) { int rv; pthread_mutex_lock(&mq->m_mutex); rv = CD_FALSE; if( !mq->m_is_empty && (mq->m_write_index==mq->m_read_index) ) { rv = CD_TRUE; } pthread_mutex_unlock(&mq->m_mutex); return rv; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void thr_fn(void *arg) { int err, signo; for ( ; ; ) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (sgino) { case SIGINT: print("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return (0); default: print("unexpected signal %d\\n", signo); exit(1); } } } int main(int argc, char **argv) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "sig_block error"); if ((err = pthread_create(&tid, 0, thr_fn, 0)) != 0) err_exit(err, "can not create thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&wait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) != 0) err_sys("sig_setmask error"); exit(0); }
1
#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, 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 on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> double accounts[4]; pthread_mutex_t account_locks[4]; void* worker(void* fname) { FILE* f = fopen((char*) fname, "r"); if (!f) { fprintf(stderr, "Error could not open file '%s'!\\n", (char*) fname); } while (1) { int to, from; double amount; fscanf(f, "%d %d %lf", &to, &from, &amount); if (feof(f)) { break; } pthread_mutex_lock(&account_locks[to]); pthread_mutex_lock(&account_locks[from]); accounts[from] -= amount; accounts[to] += amount; pthread_mutex_unlock(&account_locks[to]); pthread_mutex_unlock(&account_locks[from]); } fclose(f); pthread_exit(0); } int main ( ) { pthread_t threads[2]; char fnames[2][16]; int i; for (i = 0; i < 4; i++) { accounts[i] = 100.00; pthread_mutex_init(&account_locks[i], 0); } for (i = 0; i < 2; i++) { sprintf(fnames[i], "file%d.txt", i); pthread_create(&threads[i], 0, worker, fnames[i]); } for (i = 0; i < 2; i++) { pthread_join(threads[i], 0); } printf("All transactions completed!\\n"); pthread_exit(0); }
1
#include <pthread.h> void generar_persona (); void cerrar_banio (int ids); void generar_mujer (); void generar_hombre (); void * mujer (void * arg); void * hombre (void * arg); void mujer_quiere_entrar (); void hombre_quiere_entrar (); void mujer_sale (); void hombre_sale (); void * sacarPersona (void * arg); int puente = 0; int babuinosEsperaIzq = 0; int babuinosEsperaDer = 0; int sentidoPuente = 0; int abierto = 1; pthread_mutex_t mutexPuente = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexBabuinosEsperaIzq = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexBabuinosEsperaDer = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char const *argv[]) { srand((int)time(0)); printf("Puente vacio\\n"); pthread_t salidas; pthread_create(&salidas,0,sacarPersona, 0); signal(SIGINT,cerrar_banio); while (abierto){ generar_persona(); sleep(3); } pthread_exit(0); return 0; } void cerrar_banio (int ids){ printf("Cerrando baño...\\n"); abierto = 0; } void generar_persona () { int tipoPersona = (rand() % (2 + 1 - 1)) + 1; if (tipoPersona == 1){ generar_mujer(); } else { generar_hombre(); } } void * mujer (void * arg){ mujer_quiere_entrar(); pthread_exit(0); } void * hombre (void * arg){ hombre_quiere_entrar(); pthread_exit(0); } void generar_mujer (){ pthread_t pMujer; pthread_create(&pMujer,0, mujer,(void *)1); } void generar_hombre (){ pthread_t pHombre; pthread_create(&pHombre,0, hombre,(void *)2); } void mujer_quiere_entrar (){ int imprimir; pthread_mutex_lock(&mutexMujeresEnEspera); mujeresEnEspera++; printf("Llega mujer (%d en espera)\\n", mujeresEnEspera); pthread_mutex_unlock(&mutexMujeresEnEspera); pthread_mutex_lock(&mutexBanio); imprimir = tipodDeBanio == 2 && personasEnBanio == 0; if (tipodDeBanio == 1 || tipodDeBanio == 0 || (tipodDeBanio == 2 && personasEnBanio == 0)){ tipodDeBanio = 1; personasEnBanio++; mujeresEnEspera--; printf("Entra una mujer (%d en espera)\\n",mujeresEnEspera); } pthread_mutex_unlock(&mutexBanio); if (imprimir) { printf("Baño ocupado por mujeres\\n"); } } void * sacarPersona (void * arg){ while (abierto){ pthread_mutex_lock(&mutexBanio); if (personasEnBanio > 0){ if (tipodDeBanio == 1 ){ mujer_sale(); } else { hombre_sale(); } if (personasEnBanio == 0){ printf("Sanitario vacio\\n"); } } pthread_mutex_unlock(&mutexBanio); sleep(5); } pthread_exit(0); } void hombre_quiere_entrar (){ int imprimir; pthread_mutex_lock(&mutexHombresEnEspera); hombresEnEspera++; printf("Llega hombre (%d en espera)\\n", hombresEnEspera); pthread_mutex_unlock(&mutexHombresEnEspera); pthread_mutex_lock(&mutexBanio); imprimir = tipodDeBanio == 1 && personasEnBanio == 0; if (tipodDeBanio == 2 || tipodDeBanio == 0 || (tipodDeBanio == 1 && personasEnBanio == 0)){ tipodDeBanio = 2; personasEnBanio++; hombresEnEspera--; printf("Entra un hombre (%d en espera)\\n",hombresEnEspera); } pthread_mutex_unlock(&mutexBanio); if (imprimir) { printf("Baño ocupado por hombres\\n"); } } void mujer_sale (){ personasEnBanio--; printf("Sale una mujer\\n"); } void hombre_sale () { personasEnBanio--; printf("Sale un hombre\\n"); }
0
#include <pthread.h> static pthread_mutex_t s_data_lock = PTHREAD_MUTEX_INITIALIZER; static int s_data_version = 0; static char s_data[100]; void *data_producer(void *arg) { (void) arg; fprintf(stderr, "Data producer running\\n"); srand(time(0)); while (1) { pthread_mutex_lock(&s_data_lock); snprintf(s_data, sizeof(s_data), "The lucky number is %d.", rand() % 100); s_data_version++; pthread_mutex_unlock(&s_data_lock); sleep(1 + rand() % 10); } } struct conn_state { int data_version; }; void maybe_send_data(struct mg_connection *conn) { struct conn_state *cs = (struct conn_state *) conn->connection_param; if (cs == 0) return; pthread_mutex_lock(&s_data_lock); if (cs->data_version != s_data_version) { mg_websocket_printf(conn, WEBSOCKET_OPCODE_TEXT, "%s\\n", s_data); cs->data_version = s_data_version; } pthread_mutex_unlock(&s_data_lock); } static int ev_handler(struct mg_connection *conn, enum mg_event ev) { switch (ev) { case MG_AUTH: return MG_TRUE; case MG_WS_HANDSHAKE: return MG_FALSE; case MG_WS_CONNECT: fprintf(stderr, "%s:%u joined\\n", conn->remote_ip, conn->remote_port); conn->connection_param = calloc(1, sizeof(struct conn_state)); mg_websocket_printf(conn, WEBSOCKET_OPCODE_TEXT, "Hi %p!\\n", conn); maybe_send_data(conn); return MG_FALSE; case MG_POLL: maybe_send_data(conn); return MG_FALSE; case MG_CLOSE: fprintf(stderr, "%s:%u went away\\n", conn->remote_ip, conn->remote_port); free(conn->connection_param); conn->connection_param = 0; return MG_TRUE; default: return MG_FALSE; } } int main(void) { const char *listen_port = "8080"; struct mg_server *server; const char *err; server = mg_create_server(0, ev_handler); err = mg_set_option(server, "listening_port", listen_port); if (err != 0) { fprintf(stderr, "Error setting up listener on %s: %s\\n", listen_port, err); return 1; } mg_start_thread(data_producer, 0); printf("Listening on %s\\n", listen_port); while (1) { mg_poll_server(server, 100); } return 0; }
1
#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 *idp) { int j,i; double result=0.0; int *my_id = (int*)idp; 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 %d, count = %d Threshold reached.\\n", *my_id, count); } printf("inc_count(): thread %d, count = %d, unlocking mutex\\n", *my_id, count); pthread_mutex_unlock(&count_mutex); for (j=0; j<1000; j++) result = result + (double)random(); } pthread_exit(0); } void *watch_count(void *idp) { int *my_id = (int*)idp; printf("Starting watch_count(): thread %d\\n", *my_id); pthread_mutex_lock(&count_mutex); if (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %d Condition signal received.\\n", *my_id); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; 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, inc_count, (void *)&thread_ids[0]); pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]); pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]); 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); return(0); }
0
#include <pthread.h> static uint8_t okey[64], ikey[64]; static void vlc_rand_init (void) { uint8_t key[64]; int fd = vlc_open ("/dev/urandom", O_RDONLY); if (fd == -1) return; for (size_t i = 0; i < sizeof (key);) { ssize_t val = read (fd, key + i, sizeof (key) - i); if (val > 0) i += val; } for (size_t i = 0; i < sizeof (key); i++) { okey[i] = key[i] ^ 0x5c; ikey[i] = key[i] ^ 0x36; } vlc_close (fd); } void vlc_rand_bytes (void *buf, size_t len) { static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static uint64_t counter = 0; uint64_t stamp = NTPtime64 (); while (len > 0) { uint64_t val; struct md5_s mdi, mdo; InitMD5 (&mdi); InitMD5 (&mdo); pthread_mutex_lock (&lock); if (counter == 0) vlc_rand_init (); val = counter++; AddMD5 (&mdi, ikey, sizeof (ikey)); AddMD5 (&mdo, okey, sizeof (okey)); pthread_mutex_unlock (&lock); AddMD5 (&mdi, &stamp, sizeof (stamp)); AddMD5 (&mdi, &val, sizeof (val)); EndMD5 (&mdi); AddMD5 (&mdo, mdi.buf, 16); EndMD5 (&mdo); if (len < 16) { memcpy (buf, mdo.buf, len); break; } memcpy (buf, mdo.buf, 16); len -= 16; buf = ((uint8_t *)buf) + 16; } }
1
#include <pthread.h> extern double a, h; extern int local_n; double total; pthread_mutex_t mutex; long flag = 0; sem_t sem; extern int thread_count; double f(double x){ double return_val; return_val = x*x; return return_val; } double trap(double local_a, double local_b, double h, int local_n) { double integral; double x; int i; integral = (f(local_a) + f(local_b))/2.0; x = local_a; for (i = 1; i <= local_n-1; i++) { x = local_a + i*h; integral += f(x); } integral = integral*h; return integral; } void *trap_mutex(void* rank) { double local_a; double local_b; double my_int; long my_rank = (long) rank; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; my_int = trap(local_a, local_b, local_n, h); pthread_mutex_init(&mutex, 0); pthread_mutex_lock(&mutex); total += my_int; pthread_mutex_unlock(&mutex); return 0; } void *trap_busy(void* rank) { double local_a; double local_b; double my_int; long my_rank = (long) rank; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; my_int = trap(local_a, local_b, local_n, h); while(flag != my_rank); total += my_int; flag=(flag+1)%thread_count; return 0; } void *trap_sem(void* rank) { double local_a; double local_b; double my_int; long my_rank = (long) rank; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; my_int = trap(local_a, local_b, local_n, h); sem_init(&sem, 0, 1); sem_wait(&sem); total += my_int; sem_post(&sem); sem_destroy(&sem); return 0; }
0
#include <pthread.h> int balance = 1000; int credits = 0; int debits = 0; pthread_mutex_t b_lock,c_lock,d_lock; void * transactions(void * args){ int i,v; for(i=0;i<100;i++){ v = (int) random() % 100; if( random()% 2){ pthread_mutex_lock(&b_lock); balance = balance + v; pthread_mutex_unlock(&b_lock); pthread_mutex_lock(&c_lock); credits = credits + v; pthread_mutex_unlock(&c_lock); }else{ pthread_mutex_lock(&b_lock); balance = balance - v; pthread_mutex_unlock(&b_lock); pthread_mutex_lock(&d_lock); debits = debits + v; pthread_mutex_unlock(&d_lock); } } return 0; } int main(int argc, char * argv[]){ int n_threads,i; pthread_t * threads; if(argc < 2){ fprintf(stderr, "ERROR: Require number of threads\\n"); exit(1); } n_threads = atol(argv[1]); if(n_threads <= 0){ fprintf(stderr, "ERROR: Invalivd value for number of threads\\n"); exit(1); } threads = calloc(n_threads, sizeof(pthread_t)); pthread_mutex_init(&b_lock, 0); pthread_mutex_init(&c_lock, 0); pthread_mutex_init(&d_lock, 0); for(i=0;i<n_threads;i++){ pthread_create(&threads[i], 0, transactions, 0); } for(i=0;i<n_threads;i++){ pthread_join(threads[i], 0); } printf("\\tCredits:\\t%d\\n", credits); printf("\\t Debits:\\t%d\\n\\n", debits); printf("%d+%d-%d= \\t%d\\n", 1000,credits,debits, 1000 +credits-debits); printf("\\t Balance:\\t%d\\n", balance); free(threads); pthread_mutex_destroy(&b_lock); pthread_mutex_destroy(&c_lock); pthread_mutex_destroy(&d_lock); }
1
#include <pthread.h> int global = 0x31337; void * work(void *arg) { pthread_mutex_t * m = (pthread_mutex_t *)arg; int timer_th; for (timer_th = 0; timer_th < 9; ++timer_th) { printf("CHILD THREAD: Trying take main resourse...\\n"); int r_mutex = pthread_mutex_trylock(m); if (r_mutex == 0) { printf("CHILD THREAD: Success! Main resourse: %d\\n", global); pthread_mutex_unlock(m); } else { printf("CHILD THREAD: Failed! Main resourse busy!\\n"); } sleep(1); } return 0; } int main() { pthread_mutex_t * m = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t *)); pthread_mutex_init(m, 0); pthread_t thread; pthread_create(&thread, 0, work, (void *)m); int timer; for (timer = 0; timer < 10; ++timer) { if (timer == 0) { printf("MAIN THREAD: Main resourse free.\\n"); } if (timer == 2) { pthread_mutex_lock(m); printf("MAIN THREAD: Main resourse blocked.\\n"); } if (timer == 6) { pthread_mutex_unlock(m); printf("MAIN THREAD: Main resourse free.\\n"); } sleep(1); } pthread_mutex_destroy(m); return 0; }
0
#include <pthread.h> struct chair { struct chair *next; }; struct queue { struct chair *current; struct chair *next; int chairs; int customerCount; }; struct queue theQueue; pthread_mutex_t barberLock; pthread_mutex_t customerLock; void signalCatch(int sig) { printf("Catching signal: %d\\n", sig); kill(0, sig); exit(0); } void queue_push(void) { struct chair new; struct chair *ref = theQueue.current; if (theQueue.customerCount >= theQueue.chairs) { return; } new.next = 0; while (theQueue.next != 0) { ref = ref->next; } ref->next = &new; theQueue.customerCount++; } void queue_pop(void) { struct chair *ref = theQueue.current; theQueue.customerCount--; theQueue.current = theQueue.next; if (theQueue.next != 0) { theQueue.next = theQueue.current->next; } ref = 0; } void cut_hair(void) { printf("Barber: Cutting hair!\\n"); sleep(10); printf("Barber: Finished cutting hair!\\n"); } void get_hair_cut(void) { printf("Customer: Getting hair cut!\\n"); sleep(10); printf("Customer: Finished getting hair cut!\\n"); } void barber(void *queue) { int i; int customerNumber; while (1) { i = 0; customerNumber = theQueue.customerCount; while (theQueue.customerCount == 0) { printf("Barber: Sleeping\\n"); sleep(5); } for (i = 0; i < customerNumber; i++) { cut_hair(); } } } void customer(void *queue) { if (theQueue.customerCount >= theQueue.chairs) { printf("Queue is full: Customer is leaving.\\n"); return; } pthread_mutex_lock(&customerLock); queue_push(); pthread_mutex_unlock(&customerLock); printf("Customer: In chair waiting\\n"); pthread_mutex_lock(&barberLock); get_hair_cut(); queue_pop(); pthread_mutex_unlock(&barberLock); } int main(int argc, char **argv) { struct chair mainChair; pthread_t barberThread; pthread_t customer1, customer2, customer3, customer4; void *barberFunction = barber; void *customerFunction = customer; struct sigaction sig; sig.sa_flags = 0; sig.sa_handler = signalCatch; sigaction(SIGINT, &sig, 0); mainChair.next = 0; theQueue.current = &mainChair; pthread_mutex_init(&barberLock, 0); pthread_mutex_init(&customerLock, 0); theQueue.customerCount = 0; theQueue.chairs = 3; pthread_create(&barberThread, 0, barberFunction, 0); sleep(5); pthread_create(&customer1, 0, customerFunction, 0); pthread_create(&customer2, 0, customerFunction, 0); pthread_create(&customer3, 0, customerFunction, 0); pthread_create(&customer4, 0, customerFunction, 0); while (1) { } }
1
#include <pthread.h> int pocetVolicov = 0, kruzkuje = 0; int koniec = 0; pthread_mutex_t mutexPremenne = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexUrna = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condKruzkovat = PTHREAD_COND_INITIALIZER; void kruzkuj(void) { pthread_mutex_lock(&mutexPremenne); while(kruzkuje == 3){ pthread_cond_wait(&condKruzkovat, &mutexPremenne); } kruzkuje++; pthread_mutex_unlock(&mutexPremenne); sleep(2); pthread_mutex_lock(&mutexPremenne); kruzkuje--; pthread_cond_signal(&condKruzkovat); pthread_mutex_unlock(&mutexPremenne); } void vhadzuj(void) { pthread_mutex_lock(&mutexUrna); sleep(1); pocetVolicov++; pthread_mutex_unlock(&mutexUrna); } void *volic(void *ptr) { kruzkuj(); vhadzuj(); return 0; } void *pocitaj(void *ptr){ while(!koniec){ printf("Pocet uspesnych volicov: %d\\n", pocetVolicov); sleep(5); } printf("Pocet uspesnych volicov: %d\\n", pocetVolicov); return 0; } int main(void) { pthread_t volici[100]; pthread_t pocitadlo; pthread_create(&pocitadlo, 0, &pocitaj, 0); for (int i=0; i<100; i++) { pthread_create(&volici[i], 0, &volic, 0); sleep(1); } for (int i=0; i<100; i++) pthread_join(volici[i], 0); pthread_mutex_lock(&mutexPremenne); koniec = 1; pthread_mutex_unlock(&mutexPremenne); pthread_join(pocitadlo, 0); exit(0); }
0
#include <pthread.h> struct cave { int pearlsRemain; int pearlsMovedOver; }; void *pirateA(); void *pirateB(); void *pirateC(); void *pirateD(); pthread_mutex_t mutex; struct cave piratesNew; int main() { piratesNew.pearlsRemain = 1000; piratesNew.pearlsMovedOver = 0; pthread_t tid; pthread_setconcurrency(4); while(piratesNew.pearlsRemain > 0) { pthread_create(&tid, 0, (void *(*)(void *))pirateA, 0); pthread_create(&tid, 0, (void *(*)(void *))pirateB, 0); pthread_create(&tid, 0, (void *(*)(void *))pirateC, 0); pthread_create(&tid, 0, (void *(*)(void *))pirateD, 0); } printf( "\\nThe total pearls taken by four pirates is (total) : %d \\n", piratesNew.pearlsMovedOver); pthread_exit(0); } void *pirateA() { int pearlsMoveA = 0; pthread_mutex_lock(&mutex); if(piratesNew.pearlsRemain > 0) { pearlsMoveA = (piratesNew.pearlsRemain*10)/100; if((piratesNew.pearlsRemain*10)%100 > 0) pearlsMoveA = pearlsMoveA+1; printf( "\\nPirate A has moved %d pearls", pearlsMoveA); piratesNew.pearlsRemain = (piratesNew.pearlsRemain - pearlsMoveA); piratesNew.pearlsMovedOver = (piratesNew.pearlsMovedOver + pearlsMoveA); } pthread_mutex_unlock(&mutex); } void *pirateB() { int pearlsMoveB = 0; pthread_mutex_lock(&mutex); if(piratesNew.pearlsRemain > 0) { pearlsMoveB = (piratesNew.pearlsRemain*10)/100; if((piratesNew.pearlsRemain*10)%100 > 0) pearlsMoveB = pearlsMoveB+1; printf( "\\nPirate B has moved %d pearls", pearlsMoveB); piratesNew.pearlsRemain = (piratesNew.pearlsRemain - pearlsMoveB); piratesNew.pearlsMovedOver = piratesNew.pearlsMovedOver + pearlsMoveB; } pthread_mutex_unlock(&mutex); } void *pirateC() { int pearlsMoveC = 0; pthread_mutex_lock(&mutex); if(piratesNew.pearlsRemain > 0) { pearlsMoveC = (piratesNew.pearlsRemain*15)/100; if((piratesNew.pearlsRemain*15)%100 > 0) pearlsMoveC = pearlsMoveC+1; printf( "\\nPirates C has taken %d pearls", pearlsMoveC); piratesNew.pearlsRemain = (piratesNew.pearlsRemain - pearlsMoveC); piratesNew.pearlsMovedOver = piratesNew.pearlsMovedOver + pearlsMoveC; } pthread_mutex_unlock(&mutex); } void *pirateD() { int pearlsMoveD = 0; pthread_mutex_lock(&mutex); if(piratesNew.pearlsRemain > 0) { pearlsMoveD = (piratesNew.pearlsRemain*15)/100; if((piratesNew.pearlsRemain*15)%100 > 0) pearlsMoveD = pearlsMoveD+1; printf( "\\nPirates D has taken %d pearls", pearlsMoveD); piratesNew.pearlsRemain = (piratesNew.pearlsRemain - pearlsMoveD); piratesNew.pearlsMovedOver = piratesNew.pearlsMovedOver + pearlsMoveD; } pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks ... \\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks ...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks ... \\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started ...\\n"); pause(); return 0; } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) err_exit(err, "can't install fork handlers"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread."); sleep(2); printf("parent about to fork ...\\n"); if ((pid = fork()) < 0) err_quit("fork failed"); else if (pid == 0) printf("child returned from fork\\n"); else printf("parent returned from fork\\n"); exit(0); }
0
#include <pthread.h> pthread_mutex_t rssth_http_mutex = PTHREAD_MUTEX_INITIALIZER; int http_open (const struct selector *sel) { char * URL = sel->link; struct t_url url = tokenize_url (URL); int fd = socket(PF_INET, SOCK_STREAM, 6); struct sockaddr_in in_adrs; in_adrs.sin_family = AF_INET; struct hostent *hostinfo = gethostbyname (url.hostname); in_adrs.sin_addr = *(struct in_addr *) hostinfo->h_addr_list[0]; in_adrs.sin_port = htons ((uint16_t)80); pthread_mutex_lock (&rssth_http_mutex); sleep (1); msg_debug ("connecting to", URL, 0); if (connect (fd, (struct sockaddr *) &in_adrs, sizeof (in_adrs))) { perror ("connect"); pthread_mutex_unlock (&rssth_http_mutex); return 0; } pthread_mutex_unlock (&rssth_http_mutex); FILE * netstream = fdopen (dup(fd), "r+"); if (! netstream) { perror ("stream"); return 0; } setbuf (netstream, 0); fprintf (netstream, "GET /%s HTTP/1.0\\n", url.path); fprintf (netstream, "Host: %s\\n\\n", url.hostname); char respstr[LINE_MAX]; char * chrptr; fgets(respstr, LINE_MAX, netstream); if (!strcasestr (respstr, "200 OK")) { msg_echo ("The HTTP response is of not managed type.", "\\n\\tThread:", sel->table, "\\n\\tURL:", URL, "\\n\\t---", 0); do { *(strchr(respstr, 0x0a)) = ' '; if (chrptr = strchr(respstr, 0x0d)) *chrptr = ' '; msg_echo ("\\t", respstr, 0); fgets(respstr, LINE_MAX, netstream); } while (respstr[0] != 0x0a && respstr[0] != 0x0d); fd = 0; } else { do { *(strchr(respstr, 0x0a)) = ' '; if (chrptr = strchr(respstr, 0x0d)) *chrptr = ' '; msg_debug ("\\t", respstr, 0); fgets(respstr, LINE_MAX, netstream); } while (respstr[0] != 0x0a && respstr[0] != 0x0d); } free (url.url); fclose(netstream); return fd; }
1
#include <pthread.h> struct x86_glut_frame_buffer_t { int *buffer; int width; int height; int flush_request; }; static struct x86_glut_frame_buffer_t *x86_glut_frame_buffer; void x86_glut_frame_buffer_init(void) { x86_glut_frame_buffer = xcalloc(1, sizeof(struct x86_glut_frame_buffer_t)); x86_glut_frame_buffer->flush_request = 1; } void x86_glut_frame_buffer_done(void) { if (x86_glut_frame_buffer->buffer) free(x86_glut_frame_buffer->buffer); free(x86_glut_frame_buffer); } void x86_glut_frame_buffer_clear(void) { pthread_mutex_lock(&x86_glut_mutex); if (x86_glut_frame_buffer->buffer) memset(x86_glut_frame_buffer->buffer, 0, x86_glut_frame_buffer->width * x86_glut_frame_buffer->height * sizeof(int)); pthread_mutex_unlock(&x86_glut_mutex); } void x86_glut_frame_buffer_resize(int width, int height) { pthread_mutex_lock(&x86_glut_mutex); if (width < 1 || height < 1) fatal("%s: invalid size (width = %d, height = %d)\\n", __FUNCTION__, width, height); if (x86_glut_frame_buffer->width == width && x86_glut_frame_buffer->height == height) { memset(x86_glut_frame_buffer->buffer, 0, x86_glut_frame_buffer->width * x86_glut_frame_buffer->height * sizeof(int)); goto out; } if (x86_glut_frame_buffer->buffer) free(x86_glut_frame_buffer->buffer); x86_glut_frame_buffer->buffer = xcalloc(width * height, sizeof(int)); x86_glut_frame_buffer->width = width; x86_glut_frame_buffer->height = height; out: pthread_mutex_unlock(&x86_glut_mutex); } void x86_glut_frame_buffer_pixel(int x, int y, int color) { pthread_mutex_lock(&x86_glut_mutex); if ((unsigned int) color > 0xffffff) { warning("%s: invalid pixel color", __FUNCTION__); goto out; } if (!IN_RANGE(x, 0, x86_glut_frame_buffer->width - 1)) { warning("%s: invalid X coordinate", __FUNCTION__); goto out; } if (!IN_RANGE(y, 0, x86_glut_frame_buffer->height - 1)) { warning("%s: invalid Y coordinate", __FUNCTION__); goto out; } x86_glut_frame_buffer->buffer[y * x86_glut_frame_buffer->width + x] = color; out: pthread_mutex_unlock(&x86_glut_mutex); } void x86_glut_frame_buffer_get_size(int *width, int *height) { pthread_mutex_lock(&x86_glut_mutex); if (width) *width = x86_glut_frame_buffer->width; if (height) *height = x86_glut_frame_buffer->height; pthread_mutex_unlock(&x86_glut_mutex); } void x86_glut_frame_buffer_flush_request(void) { pthread_mutex_lock(&x86_glut_mutex); x86_glut_frame_buffer->flush_request = 1; pthread_mutex_unlock(&x86_glut_mutex); } void x86_glut_frame_buffer_flush_if_requested(void) { float red; float green; float blue; int color; int width; int height; int x; int y; pthread_mutex_lock(&x86_glut_mutex); if (!x86_glut_frame_buffer->flush_request) goto out; width = x86_glut_frame_buffer->width; height = x86_glut_frame_buffer->height; glClear(GL_COLOR_BUFFER_BIT); glPointSize(1.0); glBegin(GL_POINTS); for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { color = x86_glut_frame_buffer->buffer[y * width + x]; red = (float) (color >> 16) / 0xff; green = (float) ((color >> 8) & 0xff) / 0xff; blue = (float) (color & 0xff) / 0xff; glColor3f(red, green, blue); glVertex2i(x, y); } } glEnd(); glFlush(); x86_glut_frame_buffer->flush_request = 0; out: pthread_mutex_unlock(&x86_glut_mutex); }
0
#include <pthread.h> int contador=0; pthread_cond_t condicao_contador; pthread_t threads[3]; pthread_mutex_t mutex_contador; void *incrementa(void *valor) { int i,j; for(i=0;i<50;i++) { pthread_mutex_lock(&mutex_contador); contador++; printf("O valor do contador e %d\\n",contador); if (contador == 10) { pthread_cond_signal(&condicao_contador); printf("O valor do contador e 10\\n"); } pthread_mutex_unlock(&mutex_contador); for(j=0;j<2000;j++) ; } pthread_exit(0); } void *espera(void *valor) { printf("O thread está à espera que o valor do contador seja 10\\n"); pthread_mutex_lock(&mutex_contador); while (contador < 10) { pthread_cond_wait(&condicao_contador,&mutex_contador); printf("O thread recebeu o ‘sinal’\\n"); } printf("O contador tem o valor 10\\n"); pthread_mutex_unlock(&mutex_contador); pthread_exit(0); } void main() { int i,s,estado; pthread_mutex_init(&mutex_contador, 0); pthread_cond_init(&condicao_contador,0); pthread_create(&threads[0],0,incrementa,0); pthread_create(&threads[1],0,incrementa,0); pthread_create(&threads[2],0,espera,0); for(i=0; i<3; i++) { s=pthread_join(threads[i], (void **) &estado); if (s) { perror("Erro no join"); exit(-1); } printf("O thread %d terminou com o estado %d\\n",i,estado); } pthread_mutex_destroy(&mutex_contador); pthread_cond_destroy(&condicao_contador); pthread_exit(0); }
1
#include <pthread.h> int mediafirefs_release(const char *path, struct fuse_file_info *file_info) { printf("FUNCTION: release. path: %s\\n", path); (void)path; struct mediafirefs_context_private *ctx; struct mediafirefs_openfile *openfile; struct mfconn_upload_check_result check_result; mediafirefs_flush(path, file_info); ctx = fuse_get_context()->private_data; memset(&check_result,0,sizeof(check_result)); pthread_mutex_lock(&(ctx->mutex)); openfile = (struct mediafirefs_openfile *)(uintptr_t) file_info->fh; if (openfile->is_readonly) { if (stringv_del(ctx->sv_readonlyfiles, openfile->path) != 0) { fprintf(stderr, "FATAL: readonly entry %s not found\\n", openfile->path); exit(1); } close(openfile->fd); free(openfile->path); free(openfile); pthread_mutex_unlock(&(ctx->mutex)); return 0; } if (stringv_del(ctx->sv_writefiles, openfile->path) != 0) { fprintf(stderr, "FATAL: writefiles entry %s not found\\n", openfile->path); exit(1); } close(openfile->fd); free(openfile->path); free(openfile); folder_tree_update(ctx->tree, ctx->conn, 1); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> { int fd; off_t pos; size_t nbytes; }COMPUTE_INFO,*PCOMPUTE_INFO; value_type compute(int fd,off_t pos,off_t nbytes); void thread_compute(void *param); int g_nthreads = 0; pthread_mutex_t nthreads_mutex; value_type g_final_res = 0; int main(int argc,char **argv) { int file_id = 0; int tmp_fd = 0; pid_t pid = 0; int i = 0; value_type len = 1000; int n_process = 1; struct stat stat_buf; off_t file_size = 0; pthread_t thread_id; pthread_attr_t thread_attr; PCOMPUTE_INFO pcompute_info = 0; clock_t start_time,end_time; double total_time; start_time = clock(); if(argc != 2) { printf("error to use sumfid\\n"); return -1; } if( (file_id = open(argv[1],O_RDONLY)) < 0) { printf("error to open file %s:\\n",argv[1]); exit(1); } if(fstat(file_id,&stat_buf) < 0) { printf("error to get file stat\\n"); return -1; } if( (len*n_process < stat_buf.st_size)) { n_process = stat_buf.st_size / len; } if(n_process * len < stat_buf.st_size) { ++n_process; } n_process = 128; len = stat_buf.st_size / n_process; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED); pthread_mutex_init(&nthreads_mutex,0); g_final_res = 0; pcompute_info = malloc(sizeof(COMPUTE_INFO)*(n_process+1)); for(i = 0; i < n_process; ++i) { pcompute_info[i].fd = open(argv[1],O_RDONLY); pcompute_info[i].pos = i*len ; pcompute_info[i].nbytes = len; if(pthread_create(&thread_id,&thread_attr,(void *)thread_compute,(void *)&pcompute_info[i]) != 0) { printf("pthread_create error\\n"); exit(0); } } while(g_nthreads < n_process) ; pthread_mutex_destroy(&nthreads_mutex); free(pcompute_info); end_time = clock(); total_time = (double)((end_time- start_time)/(double)CLOCKS_PER_SEC); printf("%s = %lld\\n",argv[1],g_final_res); return 0; } value_type compute(int fd,off_t pos,off_t nbytes) { int buf[(4096*4)]; off_t nread = 0; off_t ntmp = 0; off_t nlast = nbytes; off_t num_counts = 0; int n = 0; int k = 0; int i = 0; value_type sum = 0; lseek(fd,pos,0); while( (n = read(fd,buf,(4096*4))) > 0) { ntmp = nlast < (4096*4) ? nlast : (4096*4); num_counts = ntmp / 4; nlast -= ntmp; for(i = 0; i < num_counts; ++i) sum += buf[i]; if( nlast <=0 ) break; } return sum; } void thread_compute(void *param) { PCOMPUTE_INFO pinfo = (PCOMPUTE_INFO)param; value_type res = 0; res = compute(pinfo->fd,pinfo->pos,pinfo->nbytes); pthread_mutex_lock(&nthreads_mutex); g_final_res += res; ++g_nthreads; pthread_mutex_unlock(&nthreads_mutex); pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static int write_int(char const *path, int value) { int fd; static int already_warned = -1; 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 == -1) { ALOGE("write_int failed to open %s\\n", path); already_warned = 1; } return -errno; } } 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("/sys/class/backlight/pwm-backlight/brightness", brightness); 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) { pthread_t lighting_poll_thread; 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 return -EINVAL; pthread_mutex_init(&g_lock, 0); 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_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 = "NVIDIA Tegratab lights module", .author = "NVIDIA", .methods = &lights_methods, };
0
#include <pthread.h> volatile sig_atomic_t gotsigterm = 0; volatile sig_atomic_t gotsigusr1 = 0; volatile sig_atomic_t gotsigalrm = 0; static pthread_mutex_t sigalrm_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t sigalrm_owner; static unsigned int sigalrm_installed = 0; static void sigterm_handler(int sig) { gotsigterm = 128 | sig; } static void sigusr1_handler(int sig) { gotsigusr1 = 1; } static void sigalrm_handler(int sig) { gotsigalrm = 1; } int enable_sigalrm(unsigned int seconds) { sigset_t sigs; struct sigaction action; int result = 0; pthread_mutex_lock(&sigalrm_mutex); if (sigalrm_installed == 0 || pthread_equal(pthread_self(), sigalrm_owner)) { sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = sigalrm_handler; if (sigaction(SIGALRM, &action, 0) < 0) { LOGE("unable to install signal handler for SIGARLM"); result = -1; } else { sigemptyset(&sigs); sigaddset(&sigs, SIGALRM); pthread_sigmask(SIG_UNBLOCK, &sigs, 0); sigalrm_installed = 1; sigalrm_owner = pthread_self(); gotsigalrm = 0; alarm(seconds); } } else { LOGE("PROGRAM FAILURE DETECTED: two threads trying to use SIGARLM at the same time"); result = -1; } pthread_mutex_unlock(&sigalrm_mutex); return result; } int disable_sigalrm(void) { sigset_t sig; sigemptyset(&sig); sigaddset(&sig, SIGALRM); pthread_sigmask(SIG_BLOCK, &sig, 0); pthread_mutex_lock(&sigalrm_mutex); if (sigalrm_installed != 0 && pthread_equal(pthread_self(), sigalrm_owner)) { alarm(0); sigalrm_installed = 0; } pthread_mutex_unlock(&sigalrm_mutex); return 0; } void init_sighandlers(void) { sigset_t sigs; struct sigaction action; sigemptyset(&sigs); pthread_sigmask(SIG_SETMASK, &sigs, 0); sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = sigterm_handler; if (sigaction(SIGTERM, &action, 0) < 0) { LOGE("unable to install signal handler for SIGTERM"); die(EXIT_OSERR); } if (sigaction(SIGINT, &action, 0) < 0) { LOGE("unable to install signal handler for SIGINT"); die(EXIT_OSERR); } action.sa_flags = SA_RESTART; action.sa_handler = sigusr1_handler; if (sigaction(SIGUSR1, &action, 0) < 0) { LOGE("unable to install signal handler for SIGUSR1"); die(EXIT_OSERR); } gotsigterm = gotsigusr1 = 0; sigemptyset(&sigs); sigaddset(&sigs, SIGTERM); sigaddset(&sigs, SIGINT); sigaddset(&sigs, SIGUSR1); pthread_sigmask(SIG_UNBLOCK, &sigs, 0); }
1
#include <pthread.h> long value[50000]; int index; pthread_mutex_t lock; } syncarray; void init(syncarray *c) { pthread_mutex_init(&c->lock, 0); int i; for (i=0; i<50000; i++) c->value[i] = 0; c->index = 0; } int put(syncarray *c, long val) { pthread_mutex_lock(&c->lock); int store_index = c->index; if (store_index < 50000) { c->value[store_index] = val; c->index = c->index + 1; } else store_index = -1; pthread_mutex_unlock(&c->lock); return store_index; } long get(syncarray *c, int index) { pthread_mutex_lock(&c->lock); long rc = c->value[index]; pthread_mutex_unlock(&c->lock); return rc; } long sum(syncarray *c) { int i; long sum = 0; for (i=0;i<50000;i++) sum += c->value[i]; return sum; } long avg(syncarray *c) { return sum(c) / 50000; } void *worker(void *arg) { long counter = 0; struct timespec ts; syncarray *sa = (syncarray *) arg; int rc = 0; while ((rc != -1) && (counter < 25000)) { clock_gettime(CLOCK_REALTIME, &ts); counter ++; rc = put(sa,counter); } return 0; } int main (int argc, char * argv[]) { pthread_t p1; pthread_t p2; syncarray sa; init(&sa); printf("The initial sum is %ld\\n",sum(&sa)); pthread_create(&p1, 0, worker, &sa); pthread_create(&p2, 0, worker, &sa); pthread_join(p1, 0); pthread_join(p2, 0); printf("The sum is %ld\\n",sum(&sa)); printf("The avg is %ld\\n",avg(&sa)); return 0; }
0
#include <pthread.h> volatile double pi = 0.0; pthread_mutex_t pi_lock; volatile double intervals; void * process(void *arg) { register double width, localsum; register int i; register int iproc; iproc = (int)(long) arg; width = 1.0 / intervals; localsum = 0; for (i=iproc; i<intervals; i+=2) { register double x = (i + 0.5) * width; localsum += 4.0 / (1.0 + x * x); sigprocmask(SIG_BLOCK, 0, 0); } localsum *= width; pthread_mutex_lock(&pi_lock); pi += localsum; pthread_mutex_unlock(&pi_lock); return(0); } int main(int argc, char **argv) { pthread_t thread[10]; int i; intervals = 10000000; for (i = 0; i < 10; i++) { if (pthread_create(&thread[i], 0, process, (void *)(long)i)) { fprintf(stderr, "%s: cannot make thread\\n", argv[0]); exit(1); } } return 0; }
1
#include <pthread.h> pthread_t PIDARR[5]; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; bool running=1; int var1=0, var2=0; void* kjooor(void *arg){ while(running){ pthread_mutex_lock(&mutex); var1=var1+1; var2=var1; pthread_mutex_unlock(&mutex); } return 0; } void* kjor2(void *arg){ for(int i=0;i<20;i++){ pthread_mutex_lock(&mutex); printf("Number 1 is %i, number 2 is %i\\n",var1,var2); pthread_mutex_unlock(&mutex); usleep(100000); } running=0; return 0; } int main(int argc, char **argv){ pthread_create(&(PIDARR[0]),0,kjooor,0); pthread_create(&(PIDARR[1]),0,kjor2,0); pthread_join((PIDARR[0]),0); pthread_join((PIDARR[1]),0); return 0; }
0
#include <pthread.h> static pthread_mutex_t tmutex = PTHREAD_MUTEX_INITIALIZER; static char dataroot[1024]; extern char *TCID; static void tst_dataroot_init(void) { const char *ltproot = getenv("LTPROOT"); char curdir[1024]; const char *startdir; int ret; if (ltproot) { ret = snprintf(dataroot, 1024, "%s/testcases/data/%s", ltproot, TCID); } else { startdir = tst_get_startwd(); if (startdir[0] == 0) { if (getcwd(curdir, 1024) == 0) tst_brkm(TBROK | TERRNO, 0, "tst_dataroot getcwd"); startdir = curdir; } ret = snprintf(dataroot, 1024, "%s/datafiles", startdir); } if (ret < 0 || ret >= 1024) tst_brkm(TBROK, 0, "tst_dataroot snprintf: %d", ret); } const char *tst_dataroot(void) { if (dataroot[0] == 0) { pthread_mutex_lock(&tmutex); if (dataroot[0] == 0) tst_dataroot_init(); pthread_mutex_unlock(&tmutex); } return dataroot; } static int file_copy(const char *file, const int lineno, void (*cleanup_fn)(void), const char *path, const char *filename, const char *dest) { size_t len = strlen(path) + strlen(filename) + 2; char buf[len]; snprintf(buf, sizeof(buf), "%s/%s", path, filename); if (access(buf, R_OK)) return 0; safe_cp(file, lineno, cleanup_fn, buf, dest); return 1; } void tst_resource_copy(const char *file, const int lineno, void (*cleanup_fn)(void), const char *filename, const char *dest) { if (!tst_tmpdir_created()) { tst_brkm(TBROK, cleanup_fn, "Temporary directory doesn't exist at %s:%d", file, lineno); } if (dest == 0) dest = "."; const char *ltproot = getenv("LTPROOT"); const char *dataroot = tst_dataroot(); if (file_copy(file, lineno, cleanup_fn, dataroot, filename, dest)) return; if (ltproot != 0) { char buf[strlen(ltproot) + 64]; snprintf(buf, sizeof(buf), "%s/testcases/bin", ltproot); if (file_copy(file, lineno, cleanup_fn, buf, filename, dest)) return; } const char *startwd = tst_get_startwd(); if (file_copy(file, lineno, cleanup_fn, startwd, filename, dest)) return; tst_brkm(TBROK, cleanup_fn, "Failed to copy resource '%s' at %s:%d", filename, file, lineno); }
1
#include <pthread.h> void __VERIFIER_error() { abort(); }; int __VERIFIER_nondet_int() {int n; return n;} unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> const int MAX = 65536; pthread_mutex_t mutex; struct list_node_s** head; int n; int m; float memb; float ins; float del; int n_obs; int tc; int *data; struct list_node_s { int data; struct list_node_s* next; }; int Member (int value, struct list_node_s* head_p); int Insert (int value, struct list_node_s** head_pp); int Delete (int value, struct list_node_s** head_pp); void Random (int *arr, int count); void Populate (int *data); void *Execute (void *rank); void PrintStat (double *stat, int n_obs); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; n = strtol (argv[1], 0, 10); m = strtol (argv[2], 0, 10); memb = strtof (argv[3], 0); ins = strtof (argv[4], 0); del = strtof (argv[5], 0); n_obs = strtol (argv[6], 0, 10); tc = strtol (argv[7], 0, 10); data = malloc((n+m)*sizeof(int)); printf ("Input Arguments n = %d m = %d memb = %f ins = %f del = %f n_obs = %d tc = %d \\n", n, m, memb, ins, del, n_obs, tc); int count; double stat[n_obs]; double start, end; for (count = 0; count < n_obs; count++) { head = malloc(sizeof(struct list_node_s)); Random (data, n + m); Populate(data); thread_handles = malloc (tc * sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); GET_TIME(start); for (thread = 0; thread < tc; thread++) { pthread_create(&thread_handles[thread], 0, Execute, (void*) thread); } for(thread = 0; thread < tc; thread++) { pthread_join(thread_handles[thread], 0); } GET_TIME(end); pthread_mutex_destroy(&mutex); free(thread_handles); stat[count] = end - start; } PrintStat (stat, n_obs); return 0; } int Member (int value, struct list_node_s* head_p) { struct list_node_s* curr_p = head_p; while (curr_p != 0 && curr_p -> data < value ) { curr_p = curr_p -> next; } if (curr_p == 0 || curr_p -> data > value) { return 0; } else { return 1; } } int Insert (int value, struct list_node_s** head_pp) { struct list_node_s* curr_p = *head_pp; struct list_node_s* pred_p = 0; struct list_node_s* temp_p; while (curr_p != 0 && curr_p -> data < value) { pred_p = curr_p; curr_p = curr_p -> next; } if (curr_p == 0 || curr_p -> data > value) { temp_p = malloc(sizeof(struct list_node_s)); temp_p -> data = value; temp_p -> next = curr_p; if (pred_p == 0) *head_pp = temp_p; else pred_p -> next = temp_p; return 1; } else { return 0; } } int Delete (int value, struct list_node_s** head_pp) { struct list_node_s* curr_p = *head_pp; struct list_node_s* pred_p = 0; while (curr_p != 0 && curr_p -> data <value) { pred_p = curr_p; curr_p = curr_p -> next; } if (curr_p != 0 && curr_p -> data == value) { if (pred_p == 0) { *head_pp = curr_p -> next; free(curr_p); } else { pred_p -> next = curr_p -> next; free(curr_p); } return 1; } else { return 0; } } void Random (int *arr, int count) { int i; int random [MAX]; for (i = 0; i < MAX; i++) { random[i] = i; } for (i = 0; i < MAX; i++) { int swap = rand() % MAX; int temp = random[swap]; random[swap] = random[i]; random[i] = temp; } for (i = 0; i < count; i++) { arr[i] = random[i]; } } void Populate (int *data) { int i; for (i = 0; i < n; i++) { int p = Insert (data[i], head); } } void *Execute (void *rank) { int member_ops = m * memb / tc; int insert_ops = m * ins / tc; int delete_ops = m * del / tc; int i = n; while (member_ops > 0 || insert_ops > 0 || delete_ops > 0) { int temp = rand() % 3; if (temp == 0 && member_ops > 0) { pthread_mutex_lock(&mutex); Member (data[i], *head); pthread_mutex_unlock(&mutex); member_ops--; i++; } else if (temp == 1 && insert_ops > 0) { pthread_mutex_lock(&mutex); Insert (data[i], head); pthread_mutex_unlock(&mutex); insert_ops--; i++; } else if (temp == 2 && delete_ops > 0) { pthread_mutex_lock(&mutex); Delete (data[i], head); pthread_mutex_unlock(&mutex); delete_ops--; i++; } else { continue; } } } void PrintStat (double *stat, int n_obs) { double mean, sd; int i; double count = 0; for (i = 0; i < n_obs; i++) { count +=stat[i]; } mean = count / n_obs; count = 0; for (i = 0; i < n_obs; i++) { count += (stat[i]-mean)*(stat[i]-mean); } sd = sqrt(count/n_obs); printf("Average : %f\\n", mean); printf("SD : %f\\n",sd); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int count=0; struct rw_file{ FILE *srcfile; FILE *desfile; }; void thread_rw(struct rw_file *rw_file); int main(int argc,char *argv[]){ pthread_t thrd[5]; int ret; struct rw_file rw_file; if((rw_file.srcfile=fopen("./source_file","rb"))==0){ printf("can not open source file!\\n"); exit(-1); } if((rw_file.desfile=fopen("./dest_file","wb"))==0){ printf("can not open destination file!\\n"); exit(-1); } for(int i=0;i<5;i++){ ret = pthread_create(&thrd[i],0,(void *)thread_rw,(void *)&rw_file); } for(int i=0;i<5;i++){pthread_join(thrd[i],0);} printf("This is main process :%x:All threads have done!\\n",(int)pthread_self()); fclose(rw_file.srcfile); fclose(rw_file.desfile); return 0; } void thread_rw(struct rw_file *rw_file){ char buf[100]; int id=++count; while(1){ pthread_mutex_lock(&mutex); memset(buf,0,100); if(fgets(buf,100,rw_file->srcfile)!=0){ fputs(buf,rw_file->desfile); printf("This is thread %d:%x:%s\\n",id,(int)pthread_self(),buf); } else{pthread_mutex_unlock(&mutex);break;} pthread_mutex_unlock(&mutex); sleep(0.1); } }
0
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char * getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return (envbuf); } } pthread_mutex_unlock(&env_mutex); return (0); }
1
#include <pthread.h> void init_transmition(){ pthread_cond_init(&new_data,0); pthread_mutex_init(&mutex,0); pthread_cond_init(&arrived_configuration,0); pthread_mutex_init(&mutex_configuration,0); stop = 0; pthread_create(&transmition_thread, 0, transmition, 0); } void init_fifos(int* fifo_configuration_fd) { if (mkfifo("/tmp/FIFOCONFIGURATION", S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) != 0) { if (errno != EEXIST) { perror("Creating the fifo FIFOCONFIGURATION. Error"); exit(1); } } if ((*fifo_configuration_fd = open("/tmp/FIFOCONFIGURATION", O_RDONLY)) < 0) { perror("Opening the fifo for reading. Error"); exit(2); } } void end_fifos(int fifo_configuration_fd) { close(fifo_configuration_fd); } void end_transmition() { stop = 1; pthread_join(transmition_thread, 0); pthread_cond_destroy(&new_data); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&arrived_configuration); pthread_mutex_destroy(&mutex_configuration); } void *transmition(void *p_data) { int fifo_configuration_fd = 0; char buffer = '0'; int bufferRead[5] = {0}; FILE* file = 0; if( (file = fopen("/tmp/imageTemp.txt", "w")) == 0) { exit(-2); } init_fifos(&fifo_configuration_fd); pthread_mutex_lock(&mutex_configuration); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { bufferRead[i] *= 10; if(!read(fifo_configuration_fd, &buffer, sizeof(char))) { fprintf(stdout, "Couldn't read\\n"); fflush(stdout); } bufferRead[i] += buffer-48; } } the_data.nb_images = bufferRead[0]; the_data.ramp_size = bufferRead[1]; the_data.ramp_position = bufferRead[2]; the_data.buffer_size = bufferRead[3]; the_data.decimation = bufferRead[4]; the_data.data_length = the_data.buffer_size+1; the_data.data = malloc(the_data.data_length*sizeof(char)); pthread_cond_signal(&arrived_configuration); pthread_mutex_unlock(&mutex_configuration); while(!stop) { pthread_mutex_lock(&mutex); pthread_cond_wait(&new_data, &mutex); fprintf(file, "%s\\n", the_data.data); fflush(stdout); pthread_mutex_unlock(&mutex); } end_fifos(fifo_configuration_fd); free(the_data.data); fprintf(stdout, "Everything was closed\\n"); fflush(stdout); pthread_exit(0); }
0
#include <pthread.h> extern int search_file_list(long f_inode,struct file_lock **add_loc); extern void delete_file_list(struct file_lock *ptr_file_node); extern int tr_yaffs_close_abort (int handle, unsigned int txnid); struct file_lock *resume(long f_inode,char *file_path,int f_flags,int txnid) { int search_ret; struct file_lock *loc=0,*inserted_pos; pthread_mutex_lock(&file_mutex); search_ret= search_file_list(f_inode,&loc); inserted_pos = insert_file_list(f_inode,file_path,f_flags,txnid,search_ret,loc); return inserted_pos; } void free_write_at(struct file_lock *file_to_write) { struct write_records *ptr_write_at, *foll_write_at; ptr_write_at = file_to_write->writes_at; while(ptr_write_at != 0) { foll_write_at = ptr_write_at; ptr_write_at = ptr_write_at->next; free(foll_write_at); } return; } void release_locks_on_abort(int txnid) { struct txn_node *ptr_txn_node; struct file_lock *txn_id_file_list,*ptr_file_lock; struct wait_node *wait_list_loc; fflush(stdout); pthread_mutex_lock(&txn_mutex); ptr_txn_node = head_txn_list; while(ptr_txn_node->txn_id != txnid) ptr_txn_node = ptr_txn_node->next; pthread_mutex_unlock(&txn_mutex); txn_id_file_list = ptr_txn_node->file_rec_no; ptr_txn_node->file_rec_no = 0; pthread_mutex_lock(&file_mutex); fflush(event_log); while(txn_id_file_list != 0) { ptr_file_lock = txn_id_file_list; if ((ptr_file_lock->flags != 0)&&(ptr_file_lock->writes_at != 0)) free_write_at(ptr_file_lock); wait_list_loc = search_wait_list(ptr_file_lock->file_inode); txn_id_file_list = txn_id_file_list->next_txn; if (wait_list_loc == 0) { if(ptr_file_lock->fd >=0) tr_yaffs_close_abort (ptr_file_lock->fd, txnid); delete_file_list(ptr_file_lock); } else { if(ptr_file_lock->file_mode == 0) { if((ptr_file_lock->next_shared_rec == 0) && (ptr_file_lock->prev_shared_rec == 0)) { if(ptr_file_lock->fd >=0) tr_yaffs_close_abort (ptr_file_lock->fd, txnid); delete_file_list(ptr_file_lock); wake_up(wait_list_loc); } else { if((ptr_file_lock->next_shared_rec == 0)&&(ptr_file_lock->prev_shared_rec !=0)) (ptr_file_lock->prev_shared_rec)->next_shared_rec = 0; if((ptr_file_lock->prev_shared_rec == 0)&&(ptr_file_lock->next_shared_rec != 0)) (ptr_file_lock->next_shared_rec)->prev_shared_rec = 0; if((ptr_file_lock->next_shared_rec != 0) && (ptr_file_lock->prev_shared_rec != 0)) { (ptr_file_lock->prev_shared_rec)->next_shared_rec = ptr_file_lock->next_shared_rec; (ptr_file_lock->next_shared_rec)->prev_shared_rec = ptr_file_lock->prev_shared_rec; } if(ptr_file_lock->fd >=0 ) tr_yaffs_close_abort (ptr_file_lock->fd, txnid); delete_file_list(ptr_file_lock); } } else { if(ptr_file_lock->fd >= 0) tr_yaffs_close_abort (ptr_file_lock->fd, txnid); delete_file_list(ptr_file_lock); wake_up(wait_list_loc); } } } pthread_mutex_unlock(&file_mutex); }
1
#include <pthread.h> int counter = 0; int semaphore_place = 0; pthread_mutex_t mtx_geton_passenger, mtx_getdown_passenger; pthread_cond_t cond_passenger, cond_bus, cond_stay; void *passengerAction(void *ptr){ int *id = (int *)ptr; while (1) { pthread_mutex_lock(&mtx_geton_passenger); printf("[%d] is waitting!\\n", *id); pthread_cond_wait(&cond_bus, &mtx_geton_passenger); if (semaphore_place == 0 && counter < 5) { semaphore_place = 1; printf("[%d] gets on the bus!\\n", *id); counter++; } if (counter == 5) { printf("Driver, we can go now!\\n"); pthread_cond_signal(&cond_passenger); } else { semaphore_place = 0; pthread_cond_signal(&cond_bus); } pthread_mutex_unlock(&mtx_geton_passenger); while (1) { pthread_mutex_lock(&mtx_getdown_passenger); printf("[%d] is waitting for destination to get down the bus!\\n", *id); pthread_cond_wait(&cond_stay, &mtx_getdown_passenger); if (semaphore_place == 1 && counter > 0) { semaphore_place = 0; printf("[%d] gets down the bus!\\n", *id); counter--; } if (counter == 0) { printf("Driver, we have already left!\\n"); pthread_cond_signal(&cond_passenger); } else { semaphore_place = 1; pthread_cond_signal(&cond_stay); } pthread_mutex_unlock(&mtx_getdown_passenger); break; } return 0; } return 0; } void *busAction(void *bptr){ while (1) { pthread_mutex_lock(&mtx_geton_passenger); printf("I am waitting for passenger to get on the bus!\\n"); pthread_cond_signal(&cond_bus); pthread_cond_wait(&cond_passenger, &mtx_geton_passenger); printf("I am driving!\\n"); sleep(2); printf("We have arrived! All passengers can get down the bus\\n"); pthread_mutex_lock(&mtx_getdown_passenger); printf("I am waitting for passenger to get down the bus\\n"); pthread_cond_signal(&cond_stay); pthread_cond_wait(&cond_passenger, &mtx_getdown_passenger); printf("Now the others can get on the bus!\\n"); pthread_mutex_unlock(&mtx_getdown_passenger); pthread_mutex_unlock(&mtx_geton_passenger); } return 0; } int main(){ int i; pthread_t passenger[15], bus; pthread_mutex_init(&mtx_getdown_passenger, 0); pthread_mutex_init(&mtx_geton_passenger, 0); pthread_cond_init(&cond_passenger, 0); pthread_cond_init(&cond_bus, 0); pthread_cond_init(&cond_stay, 0); int *id = malloc(15*sizeof(int)); for (i = 0; i < 15; i++) { id[i] = i; pthread_create(&passenger[i], 0, passengerAction, (void *)&id[i]); } pthread_create(&bus, 0, busAction, 0); pthread_join(bus, 0); for (i = 0; i < 15; i++) { pthread_join(passenger[i], 0); } return 0; }
0
#include <pthread.h> static void * thread_compteur (void * inutile); static void * thread_signaux (void * inutile); static int compteur = 0; static pthread_mutex_t mutex_compteur = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_compteur = PTHREAD_COND_INITIALIZER; static pthread_t thr_signaux; static pthread_t thr_compteur; int main (void) { sigset_t masque; sigfillset (& masque); pthread_sigmask (SIG_BLOCK, & masque, 0); pthread_create (& thr_signaux, 0, thread_signaux, 0); pthread_create (& thr_compteur, 0, thread_compteur, 0); pthread_exit (0); } static void * thread_compteur (void * inutile) { while (compteur < 5 ) { pthread_mutex_lock (& mutex_compteur); pthread_cleanup_push (pthread_mutex_unlock, (void *) & mutex_compteur); pthread_cond_wait (& cond_compteur, & mutex_compteur); fprintf (stdout, "Compteur : %d \\n", compteur); pthread_cleanup_pop (1); } pthread_cancel (thr_signaux); return (0); } static void * thread_signaux (void * inutile) { sigset_t masque; int numero; sigemptyset (& masque); sigaddset (& masque, SIGINT); sigaddset (& masque, SIGQUIT); while (1) { sigwait (& masque, & numero); pthread_mutex_lock (& mutex_compteur); switch (numero) { case SIGINT : compteur ++; break; case SIGQUIT : compteur --; break; } pthread_cond_signal (& cond_compteur); pthread_mutex_unlock (& mutex_compteur); } return (0); }
1
#include <pthread.h> int threads_activos; pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER; int fib_secuencial(int n) { if(n < 2) return n; return (fib_secuencial(n-1) + fib_secuencial(n-2)); } void *fib(void *p) { unsigned int n = *(int*)p; if (n < 2) return 0; else if(threads_activos >= 3 || n <= 30) { *(int*)p = fib_secuencial(n); return 0; } else { pthread_mutex_lock(&l); threads_activos+=2; pthread_mutex_unlock(&l); int x, y; pthread_t t1, t2; x = n-1; y = n-2; pthread_create(&t1, 0,fib, &x); pthread_create(&t2, 0,fib, &y); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_lock(&l); threads_activos-=2; pthread_mutex_unlock(&l); *(int*)p = x+y; } return 0; } int main(int argc, char *argv[]) { int n; threads_activos = 0; if (argc != 2) { fprintf(stderr, "Usage: fib [<cilk options>] <n>\\n"); return 0; } n = atoi(argv[1]); fib(&n); printf("Result: %d\\n", n); return 0; }
0
#include <pthread.h> { char** m_que; int m_flag; int m_capacity; int m_size; int m_front,m_tail; pthread_mutex_t m_lock; pthread_cond_t m_pro,m_con; }QUE,*pQUE; void* thd_func(void* arg); void put(pQUE pq,char* src); void get(pQUE pq,char* dest); int main(int argc,char* argv[]) { QUE aque; memset(&aque,0,sizeof(QUE)); int nthds=atoi(argv[1]); aque.m_capacity=atoi(argv[2]); aque.m_que=(char**)calloc(aque.m_capacity,sizeof(char*)); int index; for(index=0;index<aque.m_capacity;index++) { aque.m_que[index]=(char*)calloc(128,sizeof(char)); } aque.m_size=0; aque.m_front=0; aque.m_tail=-1; pthread_mutex_init(&aque.m_lock,0); pthread_cond_init(&aque.m_pro,0); pthread_cond_init(&aque.m_con,0); pthread_t* thd_arr=(pthread_t*)calloc(nthds,sizeof(pthread_t)); int* ntasks=(int*)calloc(nthds,sizeof(int)); for(index=0;index<nthds;index++) { pthread_create(thd_arr+index,0,thd_func,(void*)&aque); } char buf[128]; while(memset(buf,0,128),fgets(buf,128,stdin)!=0) { put(&aque,buf); } strcpy(buf,"over"); put(&aque,buf); for(index=0;index<nthds;index++) { pthread_join(thd_arr[index],(void*)(ntasks+index)); } for(index=0;index<nthds;index++) { printf("%d ",ntasks[index]); } printf("\\n"); pthread_mutex_destroy(&aque.m_lock); pthread_cond_destroy(&aque.m_pro); pthread_cond_destroy(&aque.m_con); return 0; } void put(pQUE pq,char* src) { pthread_mutex_lock(&pq->m_lock); while(pq->m_size==pq->m_capacity) { pthread_cond_wait(&pq->m_pro,&pq->m_lock); sleep(3); } pq->m_tail=(pq->m_tail+1) % pq->m_capacity; strcpy(pq->m_que[pq->m_tail],src); pq->m_size++; pthread_mutex_unlock(&pq->m_lock); pthread_cond_broadcast(&pq->m_con); } void get(pQUE pq,char* dest) { pthread_mutex_lock(&pq->m_lock); while(pq->m_flag==0 && pq->m_size==0) { pthread_cond_wait(&pq->m_con,&pq->m_lock); } if(pq->m_flag==1) { dest[0]=0; pthread_mutex_unlock(&pq->m_lock); return; } strcpy(dest,pq->m_que[pq->m_front]); pq->m_size--; pq->m_front=(pq->m_front+1) % pq->m_capacity; pthread_mutex_unlock(&pq->m_lock); pthread_cond_signal(&pq->m_pro); } void* thd_func(void* arg) { pQUE pq=(pQUE)arg; char buf[128]; int ncnt=0; while(1) { memset(buf,0,128); get(pq,buf); if(buf[0]==0) { pthread_cond_broadcast(&pq->m_con); printf("%u exit!\\n",pthread_self()); pthread_exit((void*)ncnt); } printf("%u get %s\\n",pthread_self(),buf); if(strcmp("over",buf)==0) { pq->m_flag=1; pthread_cond_broadcast(&pq->m_con); pthread_exit((void*)ncnt); } ncnt++; } }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for( i=0; i<(400); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for( i=0; i<(400); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> void init_tswm(struct tsWordTree* tree){ if(tree != 0) { tree->head = (struct tsTreeNode*)malloc(sizeof(struct tsTreeNode)); memset(tree->head, 0, sizeof(struct tsTreeNode)); pthread_mutex_init(&tree->head->nodeUse, 0); tree->wordCount = 0; } } void addWord_tswm(struct tsWordTree* tree, char* word) { internalAdd(tree->head, word); tree->wordCount++; } void internalAdd(struct tsTreeNode* currentNode, char* word) { pthread_mutex_lock(&currentNode->nodeUse); if(*currentNode->word == '\\0') { strcpy(currentNode->word, word); currentNode->count = 1; pthread_mutex_unlock(&currentNode->nodeUse); } else if(strcmp(word, currentNode->word) == 0) { currentNode->count++; pthread_mutex_unlock(&currentNode->nodeUse); } else if(strcmp(word, currentNode->word) < 0) { if(currentNode->lesser == 0) { currentNode->lesser = (struct tsTreeNode*)malloc(sizeof(struct tsTreeNode)); memset(currentNode->lesser, 0, sizeof(struct tsTreeNode)); pthread_mutex_init(&currentNode->lesser->nodeUse, 0); } pthread_mutex_unlock(&currentNode->nodeUse); internalAdd(currentNode->lesser, word); } else if(strcmp(word, currentNode->word) > 0) { if(currentNode->greater == 0) { currentNode->greater = (struct tsTreeNode*)malloc(sizeof(struct tsTreeNode)); memset(currentNode->greater, 0, sizeof(struct tsTreeNode)); pthread_mutex_init(&currentNode->greater->nodeUse, 0); } pthread_mutex_unlock(&currentNode->nodeUse); internalAdd(currentNode->greater, word); } } uint32_t getSize(struct tsTreeNode* currentNode) { uint32_t sizeL = 0; uint32_t sizeG = 0; if(currentNode->lesser == 0 && currentNode->greater == 0) { return 0; } if(currentNode->lesser != 0) { sizeL = getSize(currentNode->lesser); } if(currentNode->greater != 0) { sizeG = getSize(currentNode->greater); } return 1 + max(sizeG, sizeL); } uint32_t max(uint32_t a, uint32_t b) { if(a > b) { return a; }else { return b; } } void printTree(struct tsWordTree* tree) { internalPrint(tree->head); printf("Total words: %d\\n", tree->wordCount); } void internalPrint(struct tsTreeNode* currentNode) { printf("%d %s\\n", currentNode->count, currentNode->word); if(currentNode->lesser != 0) { internalPrint(currentNode->lesser); } if(currentNode->greater != 0) { internalPrint(currentNode->greater); } } void cleanup_tswt(struct tsWordTree* tree) { if(tree != 0 && tree->head != 0) { internalCleanup(tree->head); free(tree->head); } } void internalCleanup(struct tsTreeNode* currentNode) { if(currentNode->lesser != 0) { internalCleanup(currentNode->lesser); free(currentNode->lesser); } if(currentNode->greater != 0) { internalCleanup(currentNode->greater); free(currentNode->greater); } }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> { int add; int take; int buffer[10]; }product; product proBuff = {0,0,{0}}; unsigned int proId = 1; pthread_mutex_t mutex; sem_t full; sem_t empty; void *Gen(void *id) { while(1) { sem_wait(&empty); pthread_mutex_lock(&mutex); if(!(((proBuff.add + 1) % 10 ) == proBuff.take)) { proBuff.buffer[proBuff.add] = proId++; proBuff.add = (proBuff.add + 1) % 10; } else { printf("no place to enter \\n",(long*)id); } pthread_mutex_unlock(&mutex); sem_post(&full); sleep(1); } } void *Take(void *id) { while(1) { sem_wait(&full); pthread_mutex_lock(&mutex); if(!(proBuff.add == proBuff.take)) { proBuff.buffer[proBuff.take] = 0; proBuff.take = (proBuff.take + 1) % 10 ; } else { } pthread_mutex_unlock(&mutex); sem_post(&empty); sleep(1); } } int main(int argc, char *argv[]) { unsigned int buyers = 260; unsigned int providers = 4; pthread_t pro[providers]; pthread_t* bu; int t1 = pthread_mutex_init(&mutex, 0); int t2 = sem_init(&full, 0, 0); int t3 = sem_init(&empty, 0, 10); if(t1!=0||t2!=0||t3!=0) printf("Intialization Error"); bu = malloc(buyers*sizeof(pthread_t)); long i; for(i=0;i<providers;i++) pthread_create(&pro[i], 0, Gen, (void*) i); for(i=0;i<buyers;i++) pthread_create(&bu[i], 0, Take, (void*) i); for(i=0;i<providers;i++) pthread_join(pro[i], 0); for(i=0;i<buyers;i++) pthread_join(bu[i], 0); pthread_mutex_destroy(&mutex); sem_destroy(&full); sem_destroy(&empty); return 0; }
1
#include <pthread.h> static int top=0; unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=0; void *t1(void *arg) { for(int i=0; i<(5); i++) { pthread_mutex_lock(&m); assert(top!=(5)); arr[top]=i; top++; printf("pushed element %d\\n", i); pthread_mutex_unlock(&m); } } void *t2(void *arg) { for(int i=0; i<(5); i++) { pthread_mutex_lock(&m); if (top>0) { assert(top!=0); top--; printf("poped element: %d\\n", arr[top]); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> static int ensure_capacity(struct charbuffer *b, int size) { if (size > b->size) { char *newbuffer = (char *) malloc(size); if (!newbuffer) return CHARBUFFER_ERROR; if (b->buffer) { memcpy(newbuffer, b->buffer, b->size); free(b->buffer); } b->size = size; b->buffer = newbuffer; } return CHARBUFFER_OK; } int charbuffer_put(struct charbuffer *b, char *src, int len) { if (0 != pthread_mutex_lock(&b->mutex)) { return CHARBUFFER_ERROR; } if (ensure_capacity(b, b->pos + len + 64) == CHARBUFFER_ERROR) return CHARBUFFER_ERROR; memcpy(b->buffer + b->pos, src, len); b->pos += len; b->buffer[b->pos] = '\\0'; pthread_mutex_unlock(&b->mutex); return CHARBUFFER_OK; } int charbuffer_add(struct charbuffer *b, char c) { if (0 != pthread_mutex_lock(&b->mutex)) { return CHARBUFFER_ERROR; } ensure_capacity(b, b->pos + (b->pos % 64) + 1); b->buffer[b->pos++] = c; b->buffer[b->pos] = '\\0'; pthread_mutex_unlock(&b->mutex); return CHARBUFFER_OK; }
1
#include <pthread.h> int MAX = 20001; int p_sleep; int c_sleep; int producer_count; int consumer_count; int item_p; int item_c; bool isproducersleeping = 0; bool isconsumersleeping = 0; pthread_mutex_t lock; pthread_cond_t cond_consume; pthread_cond_t cond_produce; struct Queue { int front, rear, size; unsigned capacity; int* array; }; struct Queue* createQueue(unsigned capacity) { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity - 1; queue->array = (int*) malloc(queue->capacity * sizeof(int)); return queue; } int isFull(struct Queue* queue) { return (queue->size == queue->capacity); } int isEmpty(struct Queue* queue) { return (queue->size == 0); } void enqueue(struct Queue* queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1)%queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; } int dequeue(struct Queue* queue) { if (isEmpty(queue)) return 0; int item = queue->array[queue->front]; queue->front = (queue->front + 1)%queue->capacity; queue->size = queue->size - 1; return item; } void* produce(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(producer_count<MAX) { pthread_mutex_lock(&lock); while(isFull(q) == 1) { pthread_cond_wait(&cond_consume, &lock); if(!isproducersleeping){ isproducersleeping=1; p_sleep++; } } enqueue(q,producer_count); printf("Produced something. %d\\n",producer_count); producer_count++; isproducersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_consume); usleep(50000); } pthread_exit(0); } void* consume(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(consumer_count<MAX){ pthread_mutex_lock(&lock); while(isEmpty(q) == 1){ pthread_cond_wait(&cond_produce, &lock); if(!isconsumersleeping){ isconsumersleeping=1; c_sleep++; } } int output = dequeue(q); printf("Consumed item: %d \\n",output); if((output)==(MAX-1)){ printf("Total sleeps: Prod = %d Cons = %d \\n",p_sleep,c_sleep); exit(0); } consumer_count++; isconsumersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_produce); usleep(50000); } pthread_exit(0); } int main() { struct Queue* q = createQueue(20); c_sleep = 0; p_sleep = 0; producer_count = 0; consumer_count = 0; item_p = 0; item_c = 0; while(1){ pthread_mutex_init(&lock, 0); pthread_cond_init(&cond_consume, 0); pthread_cond_init(&cond_produce, 0); pthread_t producers1, producers2; pthread_t consumers1, consumers2; pthread_create(&producers1, 0, produce, q); pthread_create(&producers2, 0, produce, q); pthread_create(&consumers1, 0, consume, q); pthread_create(&consumers2, 0, consume, q); } pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond_consume); pthread_cond_destroy(&cond_produce); return 0; }
0
#include <pthread.h> pthread_mutex_t mt = PTHREAD_MUTEX_INITIALIZER; void lock_func(void* arg) { pid_t pid; pt_t tid; pid = getpid(); tid = pthread_self(); printf("want to lock mutex, msg=%s, tid=%u\\n", (char*)arg, (uint_t)tid); pthread_mutex_lock( &mt ); printf("I[tid=%u] am using, (*|^_^|*)\\n", (uint_t)tid); sleep(10); pthread_mutex_unlock( &mt ); } void try_lock_func(void* arg) { uint_t tid = (uint_t)pthread_self(); int counter = 0; while ( pthread_mutex_trylock( &mt ) ) { sleep(1); ++counter; printf("after sleep 1s, i [tid=%u] want to try again, iter=%d.\\n", tid, counter); } printf("It is my[tid=%u] turn, so long i waited...msg=%s\\n", tid, (char*)arg); pthread_mutex_unlock( &mt ); } int main() { int rc; pt_t pt1, pt2, pt3; const char* msg1 = "block"; const char* msg2 = "unblock"; rc = pthread_create(&pt1, 0, (void*)&lock_func, (void*)msg1); if (rc != 0) { printf("create thread error : %s\\n", strerror(rc)); return 1;; } rc = pthread_create(&pt2, 0, (void*)&lock_func, (void*)msg1); if (rc != 0) { printf("create thread error : %s\\n", strerror(rc)); return 1;; } sleep(1); rc = pthread_create(&pt3, 0, (void*)&try_lock_func, (void*)msg2); if (rc != 0) { printf("create thread error : %s\\n", strerror(rc)); return 1;; } pthread_join(pt1, 0); pthread_join(pt2, 0); pthread_join(pt3, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread2 (void *arg); void *thread3 (void *arg); void *thread (void *arg) { long j = (long) arg; int i, ret; pthread_t th[2]; printf ("t%ld: running!\\n", j); for (i = 0; i < 2; i++) { ret = pthread_create (th + i, 0, thread2, (void*) j); assert (ret == 0); } for (i = 0; i < 2; i++) { ret = pthread_join (th[i], 0); assert (ret == 0); } return 0; } void *thread2 (void *arg) { long i = (long) arg; printf ("t%ld': running!\\n", i); return 0; } void *thread3 (void *arg) { (void) arg; pthread_mutex_lock(&m); pthread_mutex_unlock(&m); return 0; } int main (int argc, char ** argv) { int ret; long i; pthread_t th; (void) argc; (void) argv; ret = pthread_create (&th, 0, thread3, 0); assert (ret == 0); pthread_mutex_lock(&m); pthread_mutex_unlock(&m); pthread_mutex_lock(&m); pthread_mutex_unlock(&m); for (i = 0; i < 8; i++) { printf ("m: =======\\n"); ret = pthread_create (&th, 0, thread, (void*) i); assert (ret == 0); ret = pthread_join (th, 0); assert (ret == 0); } pthread_exit (0); }
0
#include <pthread.h> { int* carpark; int capacity; int occupied; int nextin; int nextout; int cars_in; int cars_out; pthread_mutex_t lock; pthread_cond_t space; pthread_cond_t car; pthread_barrier_t bar; } cp_t; static void* car_in_handler(void* cp_in); static void* car_out_handler(void* cp_in); static void* monitor(void* cp_in); static void initialise(cp_t* cp, int size); int main(int argc, char** argv) { if(2!=argc) { fprintf(stderr, "Usage: %s carparksize\\n", basename(argv[0])); exit(1); } cp_t ourpark; initialise(&ourpark, atoi(argv[1])); pthread_t car_in_1, car_in_2, car_out_1, car_out_2, m; pthread_create(&car_in_1, 0, car_in_handler, (void*) &ourpark); pthread_create(&car_in_2, 0, car_in_handler, (void*) &ourpark); pthread_create(&car_out_1, 0, car_out_handler, (void*) &ourpark); pthread_create(&car_out_2, 0, car_out_handler, (void*) &ourpark); pthread_create(&m, 0, monitor, (void*) &ourpark); pthread_join(car_in_1, 0); pthread_join(car_in_2, 0); pthread_join(car_out_1, 0); pthread_join(car_out_2, 0); pthread_join(m, 0); exit(0); }; static void initialise(cp_t* cp, int size) { cp->occupied = cp->nextin = cp->nextout = cp->cars_in = cp->cars_out = 0; cp->capacity = size; cp->carpark = (int*) malloc(cp->capacity*sizeof(int)); pthread_barrier_init(&cp->bar, 0, 4); if(0==cp->carpark) { fprintf(stderr, "malloc()\\n"); exit(1); } srand((unsigned int) getpid()); pthread_mutex_init(&cp->lock, 0); pthread_cond_init(&cp->space, 0); pthread_cond_init(&cp->car, 0); }; static void* car_in_handler(void* carpark_in) { cp_t* temp = (cp_t*) carpark_in; unsigned int seed; pthread_barrier_wait(&temp->bar); while(1) { usleep(rand_r(&seed)%1000000); pthread_mutex_lock(&temp->lock); while(temp->occupied==temp->capacity) pthread_cond_wait(&temp->space, &temp->lock); temp->carpark[temp->nextin] = rand_r(&seed)%10; temp->occupied++; temp->nextin++; temp->nextin %= temp->capacity; temp->cars_in++; pthread_cond_signal(&temp->car); pthread_mutex_unlock(&temp->lock); } return (void*)0; }; static void* car_out_handler(void* carpark_out) { cp_t* temp = (cp_t*) carpark_out; unsigned int seed; pthread_barrier_wait(&temp->bar); while(1) { usleep(rand_r(&seed)%1000000); pthread_mutex_lock(&temp->lock); while(temp->occupied==0) pthread_cond_wait(&temp->car, &temp->lock); temp->occupied--; temp->nextout++; temp->nextout %= temp->capacity; temp->cars_out++; pthread_cond_signal(&temp->space); pthread_mutex_unlock(&temp->lock); } return (void*)0; }; static void* monitor(void* carpark_in) { cp_t* temp = (cp_t*) carpark_in; while(1) { sleep(2); pthread_mutex_lock(&temp->lock); printf("Delta: %d\\n", temp->cars_in - temp->cars_out - temp->occupied); printf("Number of cars in carpark: %d\\n\\n", temp->occupied); pthread_mutex_unlock(&temp->lock); } return (void*)0; };
1
#include <pthread.h> struct s_block { size_t size; struct s_block *next; int f; }; void *segmentptr; int segmentsize; pthread_mutex_t mutex; void printBlock ( t_block b) { if ( b->f == 1) printf( "Block addr: %lx, size: %zu\\t is free\\n", ( unsigned long) b, b->size); else printf( "Block addr: %lx, size: %zu\\t is allocated\\n", ( unsigned long) b, b->size); } t_block insertBlock ( void * ptr, void * next, size_t s, int f){ t_block b = ( t_block) ptr; b->size = s; b->f = f; if ( next == 0) { b->next = ( t_block) ((void *) b + ((sizeof(struct s_block)) + s)); b->next->f = 1; b->next->size = (size_t) ( (segmentptr + segmentsize) - ( ( void *) b->next + (sizeof(struct s_block)))); } else { b->next = ( t_block) next; } return b; } int s_create (int size) { if ( size < 32*1024 || size > 32*1024*1024) { printf( "Invalid segment size! TERMINATING CREATE\\n"); return 0; } int i; void *endptr; char *cptr; void *vp; segmentptr = sbrk(0); segmentsize = size; vp = sbrk(size); if (vp == ((void *)-1)) { printf ("segment creation failed\\n"); return (-1); } endptr = sbrk(0); printf("segmentstart=%lx, segmentend=%lx, segmentsize=%lu bytes\\n", (unsigned long)segmentptr, (unsigned long)endptr, (unsigned long)(endptr - segmentptr)); printf("---starting testing segment\\n"); cptr = (char *)segmentptr; for (i = 0; i < size; ++i) cptr[i] = 0; printf("---segment test ended - success\\n"); pthread_mutex_lock( &mutex); insertBlock ( segmentptr, 0, 0, 1); pthread_mutex_unlock( &mutex); return (0); } t_block findBlock( size_t size) { t_block b = segmentptr; while ( b->next != 0 && !(b->f == 1 && b->size >= size) ){ b = b->next; } return (b); } void splitBlock( t_block b, size_t newsize) { t_block next = ( t_block) (( void *) b + ((sizeof(struct s_block)) + newsize)); next->size = b->size - ((sizeof(struct s_block)) + newsize); next->f = 1; next->next = ( t_block) b->next; b->size = newsize; b->next = ( t_block) next; } void *s_alloc(int objectsize) { if ( objectsize < 65 || objectsize > 64*1024) { printf( "s_alloc | Invalid object size! TERMINATING ALLOC\\n"); return 0; } t_block b = ( t_block) segmentptr; size_t s = ( size_t) (((((objectsize)-1)>>3)<<3)+8);; pthread_mutex_lock( &mutex); if ( b->f == 1) b = insertBlock ( segmentptr, 0, s, 0); else { b = findBlock ( s); if ( (int) (( ( void *) b + (sizeof(struct s_block)) + s) - segmentptr) > segmentsize){ printf( "s_alloc | Segment is full! %lx\\n", (( ( void *) b + (sizeof(struct s_block)) + s) - segmentptr)); pthread_mutex_unlock( &mutex); return 0; } if ( b->size > s && 65 < (b->size - (((sizeof(struct s_block))) + s))) splitBlock( b, s); b = insertBlock ( ( void *) b, ( void *) b->next, s, 0); } pthread_mutex_unlock( &mutex); return ( ( void *) (( unsigned long) b + ( unsigned long) (sizeof(struct s_block)))); } void mergeFree(){ t_block b = ( t_block) segmentptr; t_block temp = b; while ( b->next) { if ( b->f == 1 && b->next->f == 1) { temp = b->next; b->size += (temp->size + (sizeof(struct s_block))); if ( temp->next) b->next = b->next->next; else b->next = 0; } else { if ( b->next == 0) return; b = b->next; } } } void s_free(void *objectptr) { t_block b = ( t_block) ( objectptr - (sizeof(struct s_block))); if ( b->size != 0 && b->f == 0) { pthread_mutex_lock( &mutex); b->f = 1; mergeFree(); pthread_mutex_unlock( &mutex); } else { if ( b->f == 1) printf( "s_free | This block is already free!\\n" ); else printf( "s_free | This block is already NULL!\\n" ); return; } return; } void s_print(void) { pthread_mutex_lock( &mutex); t_block b = ( t_block) segmentptr; while ( b) { printBlock( b); b = b->next; } pthread_mutex_unlock( &mutex); return; }
0