text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct element { int value; pthread_mutex_t lock; }; struct element* buffer; int max_buffer_size; int count; int fd; pthread_mutex_t fileLock; int in; int out; pthread_mutex_t proLock; int val=0; void * producerFunction(void* args) { int i; char name[100]; sprintf(name,"[Producer %u]",(unsigned int)pthread_self()); while (1) { pthread_mutex_lock(&proLock); while (count==max_buffer_size) { char message[100]; int size =sprintf(message,"%s Buffer is full waiting 1 second\\n",name); printf("%s Buffer is full waiting 1 second\\n",name); pthread_mutex_lock(&fileLock); int rc = write(fd,message,size); if (rc<0) { fprintf(stderr,"[ERROR] Could not write to file\\n"); } pthread_mutex_unlock(&fileLock); sleep(1); } int tmp=val; pthread_mutex_lock(&buffer[in].lock); buffer[in].value=val; val++; count++; in++; in%=max_buffer_size; char message[100]; int size = sprintf(message,"%s Produced value %d\\n",name,tmp); printf("%s Produced value %d\\n",name,tmp); pthread_mutex_lock(&fileLock); int rc = write(fd,message,size); if (rc<0) { fprintf(stderr,"[ERROR] Could not write to file\\n"); } pthread_mutex_unlock(&fileLock); pthread_mutex_unlock(&buffer[(in-1+max_buffer_size)%max_buffer_size].lock); pthread_mutex_unlock(&proLock); } return 0; } void * consumerFunction(void* args) { int i; char name[100]; sprintf(name,"[Consumer %u]",(unsigned int)pthread_self()); while (1) { pthread_mutex_lock(&proLock); while (count==0) { char message[100]; int size =sprintf(message,"%s Buffer is empty waiting 1 second\\n",name); printf("%s Buffer is empty waiting 1 second\\n", name); pthread_mutex_lock(&fileLock); int rc = write(fd,message,size); if (rc<0) { fprintf(stderr,"[ERROR] Could not write to file\\n"); } pthread_mutex_unlock(&fileLock); sleep(1); } pthread_mutex_lock(&buffer[out].lock); int recv =buffer[out].value; count--; out++; out%=max_buffer_size; char message[100]; int size = sprintf(message,"%s Consumed value %d\\n",name,recv); printf("%s Consumed value %d\\n",name,recv); pthread_mutex_lock(&fileLock); int rc = write(fd,message,size); if (rc<0) { fprintf(stderr,"[ERROR] Could not write to file\\n"); } pthread_mutex_unlock(&fileLock); pthread_mutex_unlock(&buffer[(out-1+max_buffer_size)%max_buffer_size].lock); pthread_mutex_unlock(&proLock); } return 0; } int main(int argc, char* argv[]) { int i; int numConsumers,numProducers; int buffer_size; if (argc==1) { numConsumers=3; numProducers=4; buffer_size=20; } else if (argc==4) { numConsumers=atoi(argv[2]); numProducers=atoi(argv[1]); buffer_size=atoi(argv[3]); } else { fprintf(stderr,"[ERROR] Incorrect command line arguments\\n"); printf(" ./exe\\n"); printf(" ./exe <number of producers> <number of consumers> <buffer size>\\n"); return 1; } buffer = (struct element*)calloc(buffer_size,sizeof(struct element)); fd = open("log.txt",O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); max_buffer_size=buffer_size; count=0; in=0; out=0; pthread_t* pro=(pthread_t*)(calloc(numProducers,sizeof(pthread_t))); pthread_t* con=(pthread_t*)(calloc(numConsumers,sizeof(pthread_t))); for (i=0;i<numProducers;i++) { int rc = pthread_create(&pro[i],0,producerFunction,0); if (rc!=0) { fprintf(stderr,"[ERROR] could not make producer thread %d",i+1); } } for (i=0;i<numConsumers;i++) { int rc = pthread_create(&con[i],0,consumerFunction,0); if (rc!=0) { fprintf(stderr,"[ERROR] could not make consumer thread %d",i+1); } } printf("log of information printed to log.txt\\n"); sleep(15); printf("Exit the program\\n"); exit(0); }
1
#include <pthread.h> static pthread_t ui_thread; static pthread_mutex_t ui_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t ui_list_mutex = PTHREAD_MUTEX_INITIALIZER; static int initialized; static struct generic_queue_head ui_msg_queue; static int text_msg(int level, const char *msg); struct ui_msg_elm { int level; char *msg; }; static void text_ui_dispatcher(void *ptr) { int ret; int oldstate; int oldtype; struct generic_qnode *n; DEBUG_MSG("Starting Text UI dispatcher"); ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate); ret |= pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype); assert(ret == 0); DEBUG_MSG("Entering Text UI dispatcher loop"); while(1) { pthread_mutex_lock(&ui_list_mutex); if(!TAILQ_EMPTY(&ui_msg_queue)) { n = TAILQ_FIRST(&ui_msg_queue); TAILQ_REMOVE(&ui_msg_queue, n, link); text_msg(((struct ui_msg_elm*)n->ptr)->level, ((struct ui_msg_elm*)n->ptr)->msg); free(((struct ui_msg_elm*)n->ptr)->msg); free(n->ptr); free(n); } pthread_mutex_unlock(&ui_list_mutex); usleep(500); } } static int text_queue_msg(int level, const char *msg) { struct generic_qnode *n; struct ui_msg_elm *elm; n = malloc(sizeof(*n)); assert(n != 0); elm = malloc(sizeof(*elm)); assert(elm != 0); elm->level = level; elm->msg = strdup(msg); n->ptr = elm; TAILQ_INSERT_TAIL(&ui_msg_queue, n, link); return 0; } static int text_msg(int level, const char *msg) { pthread_mutex_lock(&ui_mutex); fprintf(stdout, "[UI MSG]: %d- %s\\n", level, msg); pthread_mutex_unlock(&ui_mutex); } static int text_init(void *ptr) { int ret; if(initialized) { DEBUG_MSG("Text UI already initialized"); return; } TAILQ_INIT(&ui_msg_queue); ret = pthread_create(&ui_thread, 0, (void*) &text_ui_dispatcher, 0); assert(ret == 0); initialized = 1; DEBUG_MSG("Text UI initialized"); return 0; } static int text_deinit(void *ptr) { DEBUG_MSG("Text UI deinitialized"); return 0; } static struct netmon_ui ui = { .name = "text", .ui_init = text_init, .ui_deinit = text_deinit, .ui_msg = text_msg, .ui_queue_msg = text_queue_msg }; void ui_text_main() { ui_register(&ui); DEBUG_MSG("Text UI registered"); }
0
#include <pthread.h> void keepBusy( double howLongInMillisec ); pthread_mutex_t mutex; pthread_mutexattr_t attr; pthread_cond_t cv; int balance; } Account; Account* create_account(); void deposit( Account* a, int dep ); void withdraw( Account* a, int draw ); void multiple_deposits( Account* acct ); void multiple_withdrawals( Account* acct ); main() { int i; int status; pthread_t depositorThreads[5]; pthread_t withdrawerThreads[5]; Account* account = create_account(); pthread_mutexattr_init( &attr ); pthread_mutex_init( &mutex, &attr ); pthread_cond_init( &cv, 0 ); for ( i=0; i < 5; i++ ) { pthread_create( depositorThreads + i, 0, (void*(*)(void*)) multiple_deposits, account ); pthread_create( withdrawerThreads + i, 0, (void*(*)(void*)) multiple_withdrawals, account ); } for ( i=0; i < 5; i++ ) { pthread_join( *(depositorThreads + i), (void*) &status ); pthread_join( *(withdrawerThreads + i), (void*) &status ); } } Account* create_account() { Account* a = malloc( sizeof(Account) ); a->balance = 0; return a; } void deposit( Account* a, int dep ) { pthread_mutex_lock( &mutex ); a->balance += dep; pthread_cond_broadcast( &cv ); pthread_mutex_unlock( &mutex ); } void withdraw( Account* a, int draw ) { pthread_mutex_lock( &mutex ); while ( a->balance < draw ) { pthread_cond_wait( &cv, &mutex ); } a->balance -= draw; pthread_mutex_unlock( &mutex ); } void multiple_deposits( Account* acct ) { int i = 0; int x; while ( 1 ) { x = rand() % 10; deposit( acct, x ); if ( i++ % 100 == 0 ) printf( "balance after deposits: %d\\n", acct->balance ); keepBusy( 1 ); } } void multiple_withdrawals( Account* acct ) { int x; int i = 0; while ( 1 ) { x = rand() % 10; withdraw( acct, x ); if ( i++ % 100 == 0 ) printf( "balance after withdrawals: %d\\n", acct->balance ); keepBusy( 1 ); } } void keepBusy( double howLongInMillisec ) { int ticksPerSec = CLOCKS_PER_SEC; int ticksPerMillisec = ticksPerSec / 1000; clock_t ct = clock(); while ( clock() < ct + howLongInMillisec * ticksPerMillisec ) ; }
1
#include <pthread.h> pthread_mutex_t mutex, mutex2, mutex3; time_t init_time; int cnt, cnt2; void espera_activa( int tiempo) { time_t t; t = time(0) + tiempo; while(time(0) < t); } int get_the_time(){ return (time(0) - init_time); } void *tareaA( void * args) { printf("%d::A::voy a dormir\\n", get_the_time()); sleep(3); printf("%d::A::me despierto y pillo mutex\\n", get_the_time()); pthread_mutex_lock(&mutex); printf("%d::A::incremento valor\\n", get_the_time()); ++cnt; printf("%d::A::desbloqueo mutex\\n", get_the_time()); pthread_mutex_unlock(&mutex); printf("%d::A::FINISH\\n", get_the_time()); } void *tareaM( void * args) { printf("\\t%d::M::me voy a dormir\\n", get_the_time()); sleep(2); printf("\\t%d::M::me despierto y pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t%d::M::pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t%d::M::incremento variable cnt2\\n", get_the_time()); ++cnt2; printf("\\t%d::M::libero mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t%d::M::libero mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t%d::M::FINSIH\\n", get_the_time()); } void *tareaB( void * args) { printf("\\t\\t%d::B::me voy a dormir\\n", get_the_time()); sleep(1); printf("\\t\\t%d::B::me despierto y pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t\\t%d::B::espera activa\\n", get_the_time()); espera_activa(3); printf("\\t\\t%d::B::pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t\\t%d::B::incremento cnt2\\n", get_the_time()); ++cnt2; printf("\\t\\t%d::B::suelto mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t\\t%d::B::suelto mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t\\t%d::B::FINISH\\n", get_the_time()); } int main() { pthread_t hebraA, hebraM, hebraB; pthread_attr_t attr; pthread_mutexattr_t attrM, attrM2, attrM3; struct sched_param prio; time( &init_time); cnt = 0; cnt2 = 0; printf("===DEBUG MODO \\"ON\\"===\\nEXEC_TIME::THREAD_TAG::VERBOSE_INFO\\n\\n"); pthread_mutexattr_init(&attrM); pthread_mutexattr_init(&attrM2); pthread_mutexattr_init(&attrM3); if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_INHERIT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM, 3) != 0){ printf("ERROR en __setprioceiling\\n"); } if( pthread_mutexattr_setprotocol(&attrM2, PTHREAD_PRIO_INHERIT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM2, 2) != 0){ printf("ERROR en __setprioceiling\\n"); } if( pthread_mutexattr_setprotocol(&attrM3, PTHREAD_PRIO_INHERIT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM3, 2) != 0){ printf("ERROR en __setprioceiling\\n"); } pthread_mutex_init(&mutex, &attrM); pthread_mutex_init(&mutex2, &attrM2); pthread_mutex_init(&mutex3, &attrM3); if( pthread_attr_init( &attr) != 0) { printf("ERROR en __attr_init\\n"); exit(-1); } if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){ printf("ERROR __setinheritsched\\n"); exit(-1); } if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) { printf("ERROR __setschedpolicy\\n"); exit(-1); } int error; prio.sched_priority = 1; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam %d\\n", error); exit(-1); } if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) { printf("ERROR __pthread_create \\ttipo: %d\\n", error); exit(-1); } prio.sched_priority = 2; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } prio.sched_priority = 3; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } pthread_join(hebraA, 0); pthread_join(hebraM, 0); pthread_join(hebraB, 0); return 0; }
0
#include <pthread.h> int counter = 0; pthread_mutex_t my_mutex[5]; void *test_mutex(void *tid) { int thread_id; int rnd; int *tt; tt = tid; thread_id = (int) *tt; rnd = rand() % 5; sleep(rnd); if (thread_id > 0) { pthread_mutex_lock(&my_mutex[thread_id]); } counter = counter + thread_id; thread_id, counter); thread_id = thread_id + 1; if (thread_id < 5) { pthread_mutex_unlock(&my_mutex[thread_id]); } pthread_mutex_destroy(&my_mutex[thread_id]); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t thread1[5]; int t; int ec; int thread_ids[5]; srand(time(0)); for(t=0;t<5;t++){ pthread_mutex_init(&my_mutex[t], 0); pthread_mutex_lock(&my_mutex[t]); } for(t=0;t<5;t++){ thread_ids[t] = t; printf("In main: creating thread %d\\n", t); ec = pthread_create(&thread1[t], 0, test_mutex, (void *)&thread_ids[t]); } for(t=0;t<5;t++){ pthread_join(thread1[t], 0); } printf( "the results is %d \\n",counter); pthread_exit(0); }
1
#include <pthread.h> void testerFunc (int argc, char *argv[]); void *threadAction(void *pointer); void printInfo(struct timespec begin, struct timespec end); void add_synC(long long *pointer, long long value); int iterations = 1; int numThreads = 1; int syncMethod = 0; int opt_yield = 0; int test_lock = 0; int lock = 0; pthread_mutex_t mutexAdd; void add(long long *pointer, long long value); long long *COUNTER = 0; int main(int argc, char *argv[]) { struct timespec beginning, end; clock_gettime(CLOCK_REALTIME, &beginning); testerFunc(argc, argv); clock_gettime(CLOCK_REALTIME, &end); printInfo(beginning, end); pthread_mutex_destroy(&mutexAdd); } void testerFunc (int argc, char *argv[]) { static struct option long_options[] = { {"iterations", optional_argument, 0, 'i'}, {"threads", optional_argument, 0, 't'}, {"yield", optional_argument, 0, 'y'}, {"sync", optional_argument, 0, 's'}, {0, 0, 0, 0} }; int opt; int option_index = 0; opt = getopt_long(argc, argv, "a", long_options, &option_index); while(opt != -1) { switch(opt) { case 'i': if(optarg != 0) iterations = atoi(optarg); if(iterations <=0){ fprintf(stderr, "Invalid number of iterations\\n"); exit(1); } break; case 't': if(optarg != 0) numThreads = atoi(optarg); if(iterations <=0) { fprintf(stderr, "Invalid number of threads\\n"); exit(1); } break; case 'y': opt_yield = 1; break; case 's': if(optarg[0] != '\\0'){ if(optarg[0] == 'm') { syncMethod = 1; pthread_mutex_init(&mutexAdd, 0); } else if(optarg[0] == 's') { syncMethod = 2; } else if(optarg[0] == 'c'){ syncMethod = 3; } else { fprintf(stderr, "Invalid parameter passed to sync.\\n"); exit(1); } } else { fprintf(stderr, "No value for sync passed. Default value used.\\n"); } break; } opt = getopt_long(argc, argv, "a", long_options, &option_index); } pthread_t *threads = malloc(sizeof(pthread_t)*numThreads); if(threads == 0){ fprintf(stderr, "Error allocating memory.\\n"); exit(1); } int i; int ret = 1; for(i = 0; i<numThreads; i++){ ret = pthread_create(&threads[i], 0, threadAction, (void *) &COUNTER); if(ret!=0){ fprintf(stderr, "Issue creating thread\\n"); exit(1); } } for(i = 0; i < numThreads; i++) { ret = pthread_join(threads[i], 0); if(ret != 0){ fprintf(stderr, "Isse joining threads"); exit(1); } } } void *threadAction(void *pointer) { int j; switch(syncMethod) { case 1: for(j=0; j< iterations; j++) { pthread_mutex_lock(&mutexAdd); add(pointer, 1); add(pointer, -1); pthread_mutex_unlock(&mutexAdd); } break; case 2: for(j=0; j < iterations; j++) { while(__sync_lock_test_and_set(&test_lock, 1)); add(pointer, 1); add(pointer, -1); __sync_lock_release(&test_lock); } break; case 3: for(j = 0; j < iterations; j++) { add_synC(pointer, 1); } for(j=0; j < iterations; j++) { add_synC(pointer, -1); } break; case 0: for(j=0; j < iterations; j++) { add(pointer, 1); add(pointer, -1); } break; } } void printInfo(struct timespec begin, struct timespec end){ time_t secs = (end.tv_sec - begin.tv_sec) * 1000000000; long int nsecs; if( end.tv_nsec > begin.tv_nsec) nsecs = end.tv_nsec - begin.tv_nsec; else nsecs = begin.tv_nsec- end.tv_nsec; long int totalTime = (long int) secs + nsecs; int operations = numThreads * iterations * 2; printf("%d threads x %d iterations x (add + subtract) = %d operations\\n", numThreads, iterations, operations); if(COUNTER == 0) printf("Everything worked!\\n"); else printf("Error: counter = %lld\\n", COUNTER); printf("Elapsed time: %ld ns\\n", totalTime); int perOp = totalTime / operations; printf("per operation: %d ns\\n", perOp); } void add(long long *pointer, long long value) { long long sum = *pointer + value; if(opt_yield) pthread_yield(); *pointer = sum; } void add_synC(long long *pointer, long long value) { long long original; long long sum; do{ original = *pointer; sum = original + value; }while(__sync_val_compare_and_swap(pointer, original, sum) != original); }
0
#include <pthread.h> pthread_mutex_t mutex_b; pthread_mutex_t en_espera_h; pthread_mutex_t en_espera_m; pthread_cond_t hombres_filtro; pthread_cond_t mujeres_filtro; int estado; int fila_hombres = 0; int fila_mujeres = 0; int total_p = 0; void entrar_bano(int num, pthread_mutex_t *mutex, pthread_cond_t *cond, char *tipo, int *cant) { pthread_mutex_lock(mutex); *cant = *cant - 1; printf("%s En espera %d\\n", tipo, *cant); pthread_mutex_unlock(mutex); pthread_mutex_lock(&mutex_b); total_p = total_p + 1; pthread_mutex_unlock(&mutex_b); printf("%s %d Ocupado \\n", tipo, num); usleep(rand() % 200000); pthread_mutex_lock(&mutex_b); total_p = total_p -1; pthread_mutex_unlock(&mutex_b); if (total_p == 0) { printf("Desocupado\\n"); estado = 0; pthread_cond_broadcast(cond); } } void *hombre(void *arg) { int num = *(int *) arg; while (1) { usleep(rand() % 1000000); pthread_mutex_lock(&en_espera_h); printf("El hombre %d ahora esta en espera\\n", ++fila_hombres); pthread_mutex_unlock(&en_espera_h); if (estado == 0) { estado = 1; entrar_bano(num, &en_espera_h, &mujeres_filtro, "Hombre", &fila_hombres); } else if (estado == 1) { entrar_bano(num, &en_espera_h, &mujeres_filtro, "Hombre", &fila_hombres); } else { pthread_cond_wait(&hombres_filtro, &en_espera_h); entrar_bano(num, &en_espera_h, &hombres_filtro, "Hombre", &fila_hombres); } } pthread_exit(0); } void *mujer(void *arg) { int num = *(int *) arg; while (1) { usleep(rand() % 1000000); pthread_mutex_lock(&en_espera_m); fila_mujeres++; printf("La mujer %d ahora esta en espera\\n", fila_mujeres); pthread_mutex_unlock(&en_espera_m); if (estado == 0) { estado = 2; entrar_bano(num, &en_espera_m, &hombres_filtro, "Mujer", &fila_mujeres); } else if (estado == 1) { pthread_cond_wait(&mujeres_filtro, &en_espera_h); entrar_bano(num, &en_espera_h, &mujeres_filtro, "Mujer", &fila_mujeres); } else { entrar_bano(num, &en_espera_m, &hombres_filtro, "Mujer", &fila_mujeres); } } pthread_exit(0); } int main() { pthread_cond_init(&hombres_filtro, 0); pthread_cond_init(&mujeres_filtro, 0); pthread_mutex_init(&mutex_b, 0); srand(time(0)); pthread_t hombres_t[10]; pthread_t mujeres_t[10]; int i; for (i = 0; i < 10; ++i) { pthread_create(&hombres_t[i], 0, hombre, &i); pthread_create(&mujeres_t[i], 0, mujer, &i); } for (i = 0; i < 10; ++i) { pthread_join(hombres_t[i], 0); pthread_join(mujeres_t[i], 0); } return 0; }
1
#include <pthread.h> volatile int flags[10]; volatile int wait[10]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *DoWork1(void *threadid) { flags[0] = flags[0] + 1; wait[0] = 0; pthread_exit(0); } void *DoWork2(void *threadid) { pthread_mutex_lock (&mutex); flags[0] = flags[0] + 1; pthread_mutex_unlock (&mutex); pthread_exit(0); } int main( int argc, char** argv) { pthread_t threads[1]; flags[0] = 0; wait[0] = 1; __builtin_ia32_monitor ((void *)&flags, 0, 0); pthread_create(&threads[0], 0, DoWork1, 0); while (wait[0]); pthread_create(&threads[0], 0, DoWork2, 0); int mwait_cnt = 0; do { pthread_mutex_lock (&mutex); if (flags[0] != 2) { pthread_mutex_unlock (&mutex); __builtin_ia32_mwait(0, 0); } else { pthread_mutex_unlock (&mutex); } mwait_cnt++; } while (flags[0] != 2 && mwait_cnt < 1000); if (flags[0]==2) { printf("mwait regression PASSED, flags[0] = %d\\n", flags[0]); } else { printf("mwait regression FAILED, flags[0] = %d\\n", flags[0]); } return 0; }
0
#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; }
1
#include <pthread.h> struct range { long start; long end; }; float numbers[1000000]; double sum=0.0; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; void *sumNumbersInRange(void *range); void timeval_print(struct timeval *tv) { printf("%06ld microseconds\\n", tv->tv_usec); } int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) { long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); result->tv_sec = diff / 1000000; result->tv_usec = diff % 1000000; return (diff<0); } void multiThreaded(int threadNumber, int elementNumber) { struct timeval tvBegin, tvEnd, tvDiff; gettimeofday(&tvBegin, 0); struct range rangeForThread[threadNumber]; int d; int index = elementNumber / threadNumber; int unit = index; for(d=0; d<threadNumber; d++) { rangeForThread[d].start=index - unit; rangeForThread[d].end = index; index = index + unit; } pthread_t threads[threadNumber]; int v; sum=0.0; for(v=0; v<threadNumber; v++) { pthread_create(&threads[v],0,sumNumbersInRange, &rangeForThread[v]); } for(v=0; v<threadNumber; v++) { pthread_join(threads[v],0); } printf("ThreadNO: %3d, ArraySize: %7d, Sum:%19.1f ",threadNumber, elementNumber, sum); gettimeofday(&tvEnd, 0); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); printf("Time: %ld.%06ld second\\n", tvDiff.tv_sec, tvDiff.tv_usec); } void main() { long i; srand(time(0)); for(i=0; i<1000000 ; i++) { numbers[i] = rand(); } int f = fork(); if(f==0) { multiThreaded(10,1000); multiThreaded(10,10000); multiThreaded(10,100000); multiThreaded(10,1000000); multiThreaded(100,1000); multiThreaded(100,10000); multiThreaded(100,100000); multiThreaded(100,1000000); multiThreaded(200,1000); multiThreaded(200,10000); multiThreaded(200,100000); multiThreaded(200,1000000); pthread_mutex_destroy(&lock); close(f); } } void *sumNumbersInRange(void *rangeStruct) { pthread_mutex_lock(&lock); struct range *r = (struct range *)rangeStruct; int i=0; int st = r->start; int endd= r->end; for(i=st; i<endd; i++) { sum+=numbers[i]; } pthread_mutex_unlock(&lock); pthread_exit(0); }
0
#include <pthread.h> struct sin_pkt * sin_pkt_ctor(struct sin_pkt_zone *my_zone, int zone_idx, struct netmap_ring *my_ring, int *e) { struct sin_pkt *pkt; pkt = malloc(sizeof(struct sin_pkt)); if (pkt == 0) { _SET_ERR(e, ENOMEM); return (0); } memset(pkt, '\\0', sizeof(struct sin_pkt)); SIN_TYPE_SET(pkt, _SIN_TYPE_PKT); pkt->ts = malloc(sizeof(struct timeval)); memset(pkt->ts, '\\0', sizeof(struct timeval)); pkt->my_zone = my_zone; pkt->my_ring = my_ring; pkt->zone_idx = zone_idx; pkt->my_slot = &(my_ring->slot[zone_idx]); pkt->buf = NETMAP_BUF(my_ring, pkt->my_slot->buf_idx); pthread_mutex_init(&pkt->mutex, 0); return (pkt); } void sin_pkt_dtor(struct sin_pkt *pkt) { SIN_TYPE_ASSERT(pkt, _SIN_TYPE_PKT); pthread_mutex_destroy(&pkt->mutex); free(pkt->ts); free(pkt); } unsigned int sin_pkt_setflags(struct sin_pkt *pkt, unsigned int sflags, unsigned int rflags) { unsigned int oldflags; SIN_TYPE_ASSERT(pkt, _SIN_TYPE_PKT); pthread_mutex_lock(&pkt->mutex); oldflags = pkt->flags; pkt->flags |= sflags; pkt->flags &= ~rflags; pthread_mutex_unlock(&pkt->mutex); return (oldflags); }
1
#include <pthread.h> pthread_mutex_t sharedElementMutex; pthread_cond_t canConsumeCondition; int isEmpty = 1; int isDone = 0; int numOfThreads = 0; int rc = 0; struct _linked_list* lst; int value; struct _list_node* next; struct _list_node* prev; }list_node; list_node* head; list_node* tail; int nOfElems; }linked_list; int initList(){ lst = (linked_list*)malloc(sizeof(linked_list)); lst->head = 0; lst->tail = 0; lst->nOfElems = 0; if (rc) { printf("Server: Failed list init, rc=%d.\\n", rc); return(1); } return 0; } list_node* initNode(int skfd){ list_node* node = (list_node*)malloc(sizeof(list_node)); node->value = skfd; node->next = 0; node->prev = 0; } int enqueue(list_node* node){ rc = pthread_mutex_lock(&sharedElementMutex); if (lst->nOfElems == 0){ lst->head = node; lst->tail = node; lst->nOfElems++; isEmpty++; } else { list_node* prev = lst->tail; prev->next = node; lst->tail = node; node->prev = prev; lst->nOfElems++; } rc = pthread_cond_signal(&canConsumeCondition); rc = pthread_mutex_unlock(&sharedElementMutex); return 0; } list_node* dequeue(){ list_node* node = 0; rc = pthread_mutex_lock(&sharedElementMutex); while ( isEmpty && !isDone){ rc = pthread_cond_wait(&canConsumeCondition, &sharedElementMutex); if (rc) { printf("Socket Handler Thread %u: condwait failed, rc=%d\\n", (unsigned int)pthread_self(), rc); pthread_mutex_unlock(&sharedElementMutex); exit(1); } } if (!isEmpty){ list_node* node = lst->tail; lst->tail = node->prev; lst->tail->next = 0; lst->nOfElems--; isEmpty = lst->nOfElems == 0 ? 1 : 0; } rc = pthread_mutex_unlock(&sharedElementMutex); return node; } void *handleSocket(void *parm){ list_node* node; int decfd; char recvBuff[5]; int notReaden = sizeof(recvBuff); int totalRead = 0; int nread = 0; int isClosed = 0; int res; while (!isDone || !isEmpty){ node = dequeue(); while (!isClosed && node!= 0){ decfd = node->value; while (notReaden > 0){ nread = read(decfd, recvBuff + totalRead, notReaden); if (nread < 1){ close(decfd); isClosed = 1; } totalRead += nread; notReaden -= nread; } if (totalRead == 5){ if (atoi(recvBuff) == 0){ res = setos_add(ntohl(*((uint32_t *)(recvBuff + 1))),0); write(decfd, &res, 1); } else if (atoi(recvBuff) == 1){ res = setos_remove(ntohl(*((uint32_t *)(recvBuff + 1))), 0); write(decfd, &res, 1); } else{ res = setos_contains(ntohl(*((uint32_t *)(recvBuff + 1)))); write(decfd, &res, 1); } } else{ printf("Socket Handler Thread %u: read fail,\\n", (unsigned int)pthread_self()); } } isClosed = 0; } return 0; } static void handler(int signum){ isDone = 1; } int main(int argc, char **argv){ int i; int listenfd = 0; int connfd = 0; int numOfThreads = atoi(argv[1]); struct sockaddr_in serv_addr; char sendBuff = 0; pthread_t* thread; struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); thread = (pthread_t*)malloc(numOfThreads*sizeof(pthread_t)); rc = pthread_mutex_init(&sharedElementMutex, 0); rc = pthread_cond_init(&canConsumeCondition, 0); initList(); setos_init(); for (i = 0; i <numOfThreads; i++) { rc = pthread_create(&thread[i], 0, handleSocket, 0); } sleep(2); listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[2])); if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))){ printf("\\n Error : Bind Failed. %s \\n", strerror(errno)); return 1; } if (listen(listenfd, 10)){ printf("\\n Error : Listen Failed. %s \\n", strerror(errno)); return 1; } while (!isDone) { connfd = accept(listenfd, (struct sockaddr*)0, 0); if (connfd<0){ printf("\\n Error : Accept Failed. %s \\n", strerror(errno)); pthread_exit(0); } enqueue(initNode(connfd)); } for (i = 0; i <numOfThreads; i++) { rc = pthread_mutex_lock(&sharedElementMutex); assert(!rc); pthread_cond_signal(&canConsumeCondition); rc = pthread_mutex_unlock(&sharedElementMutex); assert(!rc); } sleep(2); printf("Clean up\\n"); pthread_mutex_destroy(&sharedElementMutex); pthread_cond_destroy(&canConsumeCondition); free(thread); printf("Main completed\\n"); return 0; }
0
#include <pthread.h> int removeProduct(struct ringBuffer * buffer){ printf("\\n+--------------------------------------+\\n"); printf("+ CONSUMING AND INSERTING PRODUCT +\\n"); printf("+--------------------------------------+\\n"); int currentOut = buffer->out; struct product * data = (struct product *) &buffer[1]; data[currentOut].code = 0; strcpy( data[currentOut].name, "" ); buffer->out++; if(buffer->out == buffer->size) buffer->out = 0; printf("Product [Code: %d , Name: %s] REMOVED from Slot: %d\\n", data[currentOut].code, data[currentOut].name,currentOut); } int emptyBuffer(struct ringBuffer * buffer, int numberProducts, int semid, float sleepingTime){ int i; for (i = 0; i < numberProducts && buffer->isOpen ; i++){ printf("DECREASING Semaphore's Value - FULL.\\n"); semop(semid, &decFull, 1); printf("DECREASING Semaphore's Value - MUTEX.\\n"); semop(semid, &decMutex, 1); removeProduct(buffer); printf("INCREASING Semaphore's Value - MUTEX.\\n"); semop(semid, &incMutex, 1); printf("INCREASING Semaphore's Value - EMPTY.\\n"); semop(semid, &incEmpty, 1); printf("\\n> Buffer info - In Pointer: %d , Out Pointer: %d\\n", buffer->in, buffer->out); sleep(sleepingTime); } } void * crear_reader_e(struct hilo_rw *arg){ int semaphoreArrayIdentifier = arg->s_key; int sharedMemoryIdentifier = arg->m_key; int sleepingTime = arg->sleep; int numberProducts = arg->num_p; pthread_t h_aux; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int i; struct ringBuffer * retrieveBuffer; if ( !(sharedMemoryIdentifier < 0 || semaphoreArrayIdentifier < 0) ) { retrieveBuffer = (struct ringBuffer *)shmat(sharedMemoryIdentifier, 0, 0); if (retrieveBuffer==( struct ringBuffer *)-1) { perror("shmat"); } else { int f=0; pthread_mutex_lock (&mutex1); emptyBuffer( retrieveBuffer, numberProducts, semaphoreArrayIdentifier,sleepingTime); shmdt(retrieveBuffer); pthread_mutex_unlock (&mutex1); } } else { perror("shmget"); } crear_reader_e(arg); h_aux = pthread_self(); printf("\\n> Producer with PID: %d TERMINATED\\n",(unsigned int) h_aux); return 0; } int main(int argc, char **argv) { if(argc < 5) printf("Usage: producer <Semaphore Key> <Shared Memory Key> <Sleeping Time> <Number of Products>"); else{ int semaphoreKey = atoi(argv[1]); int sharedMemoryKey = atoi(argv[2]); int sleepingTime = atoi(argv[3]); int numberProducts = atoi(argv[4]); int i; pthread_t hilos[numberProducts]; int semaphoreArrayIdentifier; semaphoreArrayIdentifier = semget (semaphoreKey, NSEM, IPC_PRIVATE); int sharedMemoryIdentifier; char *attachedMemoryPointer; sharedMemoryIdentifier = sharedMemoryIdentifier = shmget(sharedMemoryKey, sizeof(struct ringBuffer), PERM); struct hilo_rw h_r; h_r.s_key=semaphoreArrayIdentifier; h_r.m_key=sharedMemoryIdentifier; h_r.sleep = sleepingTime; h_r.num_p = numberProducts; for(i=0;i<numberProducts;i++){ int new_reader = pthread_create(&hilos[i], 0, (void *) &crear_reader_e,(void *) &h_r); } sleep(50); for(i=1;i<numberProducts;i++){ pthread_join(hilos[i], 0); } } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_t tidP,tidC; sem_t full,empty; int counter; int buffer[10]; void initialise() { pthread_mutex_init(&mutex,0); sem_init(&full,1,0); sem_init(&empty,1,10); counter=0; } void write(int item) { buffer[counter++]=item; } int read() { return(buffer[--counter]); } void* producer(void * param) { while(1) { int wt,item,i; item=rand()%5; wt=rand()%5; sem_wait(&empty); pthread_mutex_lock(&mutex); printf("\\n Prodeucer has produced item %d \\n",item); write(item); pthread_mutex_unlock(&mutex); sem_post(&full); sleep(rand()%3); } } void* consumer(void *param) { while(1) { int wt,i,item; wt=rand()%5; sem_wait(&full); pthread_mutex_lock(&mutex); item=read(); printf("\\n Consumer has consumed item %d\\n",item); pthread_mutex_unlock(&mutex); sem_post(&empty); sleep(rand()%2); } } int main() { int n1,n2,i; initialise(); pthread_create(&tidP,0,&producer,0); pthread_create(&tidC,0,&consumer,0); pthread_join(tidP,0); pthread_join(tidC,0); exit(0); }
0
#include <pthread.h> struct msg { struct msg *m_next; void *private_data; }; struct job { struct job *j_next; struct job *j_prev; pthread_t j_id; }; struct msg *workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void process_msg(void) { struct msg *mp; for (;;) { pthread_mutex_lock(&qlock); while (workq == 0) pthread_cond_wait(&qready, &qlock); mp = workq; if(((struct job *)mp->private_data)->j_id==pthread_self()){ workq = mp->m_next; } pthread_mutex_unlock(&qlock); printf("Thread %u is running\\n",(unsigned int)pthread_self()); if(((struct job *)mp->private_data)->j_id!=pthread_self()){ printf("Thread %u didn't match jobId %u\\n",(unsigned int)pthread_self(),(unsigned int)((struct job*)mp->private_data)->j_id); sleep(1); continue; } else printf("Thread %u is handling messages\\n",(unsigned int)pthread_self()); sleep(1); } } void enqueue_msg(struct msg *mp) { pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); } struct queue { struct job *q_head; struct job *q_tail; pthread_rwlock_t q_lock; }; int queue_init(struct queue *qp) { int err; qp->q_head = 0; qp->q_tail = 0; err = pthread_rwlock_init(&qp->q_lock, 0); if (err != 0) return(err); return(0); } void job_insert(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); jp->j_next = qp->q_head; jp->j_prev = 0; if (qp->q_head != 0) qp->q_head->j_prev = jp; else qp->q_tail = jp; qp->q_head = jp; pthread_rwlock_unlock(&qp->q_lock); struct msg *mp=(struct msg *)malloc(sizeof(struct msg)); mp->private_data=(void *)jp; enqueue_msg(mp); } void job_append(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); jp->j_next = 0; jp->j_prev = qp->q_tail; if (qp->q_tail != 0) qp->q_tail->j_next = jp; else qp->q_head = jp; qp->q_tail = jp; pthread_rwlock_unlock(&qp->q_lock); struct msg *mp=(struct msg *)malloc(sizeof(struct msg)); mp->private_data=(void *)jp; enqueue_msg(mp); } void job_remove(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); if (jp == qp->q_head) { qp->q_head = jp->j_next; if (qp->q_tail == jp) qp->q_tail = 0; } else if (jp == qp->q_tail) { qp->q_tail = jp->j_prev; if (qp->q_head == jp) qp->q_head = 0; } else { jp->j_prev->j_next = jp->j_next; jp->j_next->j_prev = jp->j_prev; } pthread_rwlock_unlock(&qp->q_lock); } struct job * job_find(struct queue *qp, pthread_t id) { struct job *jp; if (pthread_rwlock_rdlock(&qp->q_lock) != 0) return(0); for (jp = qp->q_head; jp != 0; jp = jp->j_next) if (pthread_equal(jp->j_id, id)) break; pthread_rwlock_unlock(&qp->q_lock); return(jp); } void *thr_fn(void *arg) { int a=*((int *)arg); printf("thread %d is waiting: %u %u\\n",a,(unsigned int)pthread_self(),(unsigned int)getpid()); process_msg(); printf("thread %d has done: %u %u\\n",a,(unsigned int)pthread_self(),(unsigned int)getpid()); } void main() { int i; int num[10]={1,2,3,4,5,6,7,8,9,10}; int ntid[10]; for(i=0;i<3 ;++i){ int err; err=pthread_create((pthread_t *)(ntid+i),0,thr_fn,num+i); if(err != 0) err_quit("can't create thread:%s \\n",strerror(err)); } sleep(1); struct queue Q; queue_init(&Q); for(i=0;i<10;++i){ struct job *pj; pj=(struct job *)malloc(sizeof(struct job)); pj->j_id=ntid[i%3]; job_insert(&Q,pj); } sleep(10); }
1
#include <pthread.h> void philosopher_fn(void*); pthread_mutex_t mutex_arr[5]; sem_t four_chairs; int main() { int i=0; pthread_t threads[5]; for(i=0;i<5;i++){ pthread_mutex_init(&mutex_arr[i],0); } sem_init(&four_chairs,0,4); i = 0; while(i<5){ if(pthread_create(&threads[i],0,philosopher_fn,(void*)i) != 0){ perror("Error creating threads\\n"); return 1; } printf("Thread %d spawn\\n",i); i++; } for(i=0;i<5;i++){ pthread_join(threads[i],0); } return 0; } void philosopher_fn(void* no){ int i = (int)no; int right,count; right = (i+1)%5; for(count=0;count<5;count++){ printf("Philosopher %d going to think [%d]\\n",i,count); think(); sem_wait(&four_chairs); printf("Philosopher %d occupied a chair [%d]\\n",i,count); pthread_mutex_lock(&mutex_arr[i]); pthread_mutex_lock(&mutex_arr[right]); printf("Philosopher %d locked chopsticks [%d]\\n",i,count); printf("Philosopher %d going to eat [%d]\\n",i,count); eat(); printf("Philosopher %d going to unlock chopsticks [%d]\\n",i,count); pthread_mutex_unlock(&mutex_arr[right]); pthread_mutex_unlock(&mutex_arr[i]); sem_post(&four_chairs); printf("Philosopher %d gave up a chair [%d]\\n",i,count); } } void think(){ sleep(1); } void eat(){ sleep(1); }
0
#include <pthread.h> pthread_mutex_t lock; struct timeval start_time,end_time; float seq_thread_func(long int size) { int k=0; pthread_mutex_lock(&lock); long int blockSize=(long int)(20*1000000)/size; char *mem1; char *mem2; mem1=malloc(blockSize*size); mem2=malloc(blockSize*size); strncat(mem2,"hello",blockSize*size); gettimeofday(&start_time,0); for(k=0;k<(long int)(blockSize);k++) { memcpy(mem1+k,mem2+k,size); } gettimeofday(&end_time,0); double data1=(double)start_time.tv_sec+((double)start_time.tv_usec/1000000); double data2=(double)end_time.tv_sec+((double)end_time.tv_usec/1000000); float dataTime=data2-data1; free(mem1); free(mem2); printf("%f",dataTime); pthread_mutex_unlock(&lock); return dataTime; } float random_thread_func(long int size) { int random_pos=0,k; pthread_mutex_lock(&lock); long int blockSize=(1000000*20)/size; char *mem1; char *mem2; mem1=malloc(blockSize*size); mem2=malloc(blockSize*size); strncat(mem2,"hello",blockSize*size); gettimeofday(&start_time,0); for(k=0;k<(long int)blockSize;k++) { random_pos = rand()%(blockSize); memcpy(mem1+random_pos,mem2+random_pos,size); } gettimeofday(&end_time,0); double data1=(double)start_time.tv_sec+((double)start_time.tv_usec/1000000); double data2=(double)end_time.tv_sec+((double)end_time.tv_usec/1000000); float dataTime=data2-data1; free(mem1); free(mem2); printf("%f",dataTime); pthread_mutex_unlock(&lock); return dataTime; } void main() { float throughput,latency; int access; int nothreads; int operation; long int size; int i; float timeTaken=0,data=0; printf("\\n Block size:(Select 1 for 1B=1,2 for 1KB=1024,3 for 1MB=1048576):"); fflush(stdout); scanf("%d",&size); printf("Access Method : 1-Sequential 2-Random"); fflush(stdout); scanf("%d",&access); printf("Enter number of threads 1,2,4 :"); fflush(stdout); scanf("%d",&nothreads); pthread_t pth[nothreads]; if(size==2) { size=(long int)1024; } if(size==3) { size=(long int)(1024*1024); } if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } for(i=0;i<nothreads;i++) { if(access==1) pthread_create(&pth[i],0,seq_thread_func,(long int)size); else pthread_create(&pth[i],0,random_thread_func,(long int)size); } for(i=0;i<nothreads;i++) { pthread_join(pth[i],&data); timeTaken=timeTaken+data; } printf("%f",timeTaken); timeTaken=timeTaken/nothreads; latency=(float)(timeTaken*size*1000)/(2*1000000*20); printf("Latency in milliseconds : %f \\n",latency); throughput = (float)(1000000*20*2)/(timeTaken); printf("Throughput in MB/sec : %f\\n",(throughput)/(1024*1024)); int filesc; char *fs="values.txt"; filesc = open(fs,O_CREAT|O_RDWR,S_IRWXU); char *c = (char *)malloc(sizeof(char)*10000); char *s = (char *)malloc(sizeof(char)*10); s[0]='\\0'; c[0] = '\\0'; strcat(c,"\\r\\n"); strcat(c,"size"); strcat(c," "); strcat(c,"threads"); strcat(c," "); strcat(c,"access"); strcat(c," "); strcat(c,"throughput"); strcat(c," "); strcat(c,"latency"); strcat(c,"\\r\\n"); sprintf (s,"%d",(int)size); strcat(c,s); strcat(c," "); s[0]='\\0'; sprintf (s,"%d",(int)nothreads); strcat(c,s); strcat(c," "); sprintf(s,"%d",(int)access); strcat(c,s); strcat(c," "); sprintf(s,"%f",(float)throughput/(1024*1024)); strcat(c,s); strcat(c," "); s[0]='\\0'; sprintf(s,"%f",(float)latency); strcat(c,s); strcat(c,"\\r\\n"); printf("\\n c is \\n %s",c); write(filesc,c,strlen(c)); free(c); free(s); }
1
#include <pthread.h> void InitBasicQueue(int size) { CIRCLEQ_INIT(&head); CIRCLEQ_INIT(&rq_head); pthread_mutex_init(&lock, 0); } void BasicEnqueue(void* task) { struct basicentry* n = (struct basicentry*) malloc(sizeof(struct basicentry)); n->elem = task; pthread_mutex_lock(&lock); CIRCLEQ_INSERT_TAIL(&head, n, entries); pthread_mutex_unlock(&lock); } void* BasicDequeue() { struct basicentry *n; do { pthread_mutex_lock(&lock); n = CIRCLEQ_FIRST(&head); CIRCLEQ_REMOVE(&head, head.cqh_first, entries); pthread_mutex_unlock(&lock); sched_yield(); } while(!n->elem); return n->elem; } void BasicEnqueue_rq(void* task) { struct basicentry* n = (struct basicentry*) malloc(sizeof(struct basicentry)); n->elem = task; pthread_mutex_lock(&lock); CIRCLEQ_INSERT_TAIL(&rq_head, n, entries); pthread_mutex_unlock(&lock); } void* BasicDequeue_rq() { struct basicentry *n; do { pthread_mutex_lock(&lock); n = CIRCLEQ_FIRST(&rq_head); CIRCLEQ_REMOVE(&rq_head, rq_head.cqh_first, entries); pthread_mutex_unlock(&lock); sched_yield(); } while(!n->elem); return n->elem; }
0
#include <pthread.h> void thread_listen() { int sockfd, income_sockfd; struct sockaddr_in local, income; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("Listening socket"); exit(1); } socket_reuse(sockfd); local.sin_family = AF_INET; local.sin_addr.s_addr = INADDR_ANY; local.sin_port = local_port; if (bind(sockfd, (struct sockaddr *) &local, sizeof(local)) < 0) { perror("Listening port"); exit(1); } listen(sockfd, PEER_NUMBER + 1); while (1) { int len = sizeof(income); pthread_t thread; struct thread_list_t *thread_entry = malloc(sizeof(struct thread_list_t)); income_sockfd = accept(sockfd, (struct sockaddr*) &income, &len); if (income_sockfd < 0) continue; thread_entry -> id = thread; pthread_create(&thread, 0, (void * (*) (void *)) handle_main, (void *) income_sockfd); } } void handle_main(int sockfd) { char cmd[2]; pthread_detach(pthread_self()); if (read(sockfd, cmd, 2) != 2) { pthread_exit(0); } switch (cmd[0]) { case 0x02: if (!cmd[1]) { handle_trackertest(sockfd); } else { close(sockfd); } break; case 0x05: if (cmd[1] == 1) { handle_bitmap(sockfd); } else { close(sockfd); } break; case 0x06: if (cmd[1] == 2) { handle_chunk(sockfd); } else { close(sockfd); } break; default: close(sockfd); } pthread_exit(0); return; } void handle_trackertest(int sockfd) { char msg[2]; msg[0] = 0x12; msg[1] = 0; write(sockfd, msg, 2); close(sockfd); return; } void handle_bitmap(int sockfd) { unsigned int tmp, len; char *msg; if (!bitc_get(mode, 8)) goto reject; if (read(sockfd, &tmp, 4) != 4) goto reject; if (ntohl(tmp) - 4) goto reject; if (read(sockfd, &tmp, 4) != 4) goto reject; if (tmp - ntohl(fileid)) goto reject; len = (nchunk + 8) >> 3; msg = malloc(2 + 4 + len); msg[0] = 0x15; msg[1] = 1; tmp = htonl(len); memcpy(msg + 2, &tmp, 4); pthread_mutex_lock(&mutex_filebm); memcpy(msg + 2 + 4, filebitmap, len); pthread_mutex_unlock(&mutex_filebm); write(sockfd, msg, 2 + 4 + len); goto out; reject: msg = malloc(2); msg[0] = 0x25; msg[1] = 0; write(sockfd, msg, 2); out: free(msg); close(sockfd); return; } void handle_chunk(int sockfd) { char *msg; unsigned int offset, tmp, size; int filefd; if (!bitc_get(mode, 2)) goto reject; if (read(sockfd, &tmp, 4) != 4) goto reject; if (ntohl(tmp) - 4) goto reject; if (read(sockfd, &tmp, 4) != 4) goto reject; if (tmp - ntohl(fileid)) goto reject; if (read(sockfd, &tmp, 4) != 4) goto reject; if (ntohl(tmp) - 4) goto reject; if (read(sockfd, &offset, 4) != 4) goto reject; offset = ntohl(offset); if (offset >= filesize) goto reject; if ((offset + (1 << CHUNK_SIZE)) > filesize) { size = filesize - offset; } else { size = (1 << CHUNK_SIZE); } msg = malloc(2 + 4 + size); msg[0] = 0x16; msg[1] = 1; tmp = htonl(size); memcpy(msg + 2, &tmp, 4); pthread_mutex_lock(&mutex_filefd); filefd = open(filename, O_RDONLY); lseek(filefd, offset, 0); if (read(filefd, msg + 2 + 4, size) != size) { pthread_mutex_unlock(&mutex_filefd); free(msg); goto reject; } close(filefd); pthread_mutex_unlock(&mutex_filefd); sendn(sockfd, msg, size + 2 + 4); goto out; reject: msg = malloc(2); msg[0] = 0x26; msg[1] = 0; write(sockfd, msg, 2); out: free(msg); close(sockfd); return; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *idp) { int j,i; double result=0.0; long my_id = (long)idp; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_broadcast(&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 *idp) { long my_id = (long)idp; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { printf("***Before cond_wait: thread %ld\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("***Thread %ld 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[6]; 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[2], &attr, watch_count, (void *)2); pthread_create(&threads[3], &attr, watch_count, (void *)3); pthread_create(&threads[4], &attr, watch_count, (void *)4); pthread_create(&threads[5], &attr, watch_count, (void *)5); pthread_create(&threads[0], &attr, inc_count, (void *)0); pthread_create(&threads[1], &attr, inc_count, (void *)1); for (i = 0; i < 6; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 6); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t C = PTHREAD_COND_INITIALIZER; int customer_count = 0; int chair_count = 5; int flag_sleeping=0; int max_customer_count = 10; int total = 10; pthread_cond_t call_customer=PTHREAD_COND_INITIALIZER; pthread_cond_t Barber = PTHREAD_COND_INITIALIZER; pthread_cond_t Done = PTHREAD_COND_INITIALIZER; pthread_cond_t Wait = PTHREAD_COND_INITIALIZER; pthread_cond_t start_haircut=PTHREAD_COND_INITIALIZER; pthread_cond_t end_haircut =PTHREAD_COND_INITIALIZER; pthread_cond_t wake_barber=PTHREAD_COND_INITIALIZER; pthread_cond_t check_remaining = PTHREAD_COND_INITIALIZER; pthread_cond_t call_barber = PTHREAD_COND_INITIALIZER; void barber(void) { pthread_mutex_lock(&m); while(1) { if(customer_count == 0) { flag_sleeping = 1; printf("DEBUG: %f barber goes to sleep\\n", timestamp()); pthread_cond_wait(&Barber,&m); flag_sleeping = 0; } sleep_exp(1.2,&m); pthread_cond_signal(&Done); } pthread_mutex_unlock(&m); } void customer(int customer_num) { pthread_mutex_lock(&m); sleep_exp(0.1,&m); while(1) { if (customer_count >= chair_count) { printf("DEBUG: %f customer %d enters shop\\n", timestamp(), customer_num); printf("DEBUG: %f customer %d leaves shop\\n",timestamp(),customer_num); } else { customer_count++; printf("DEBUG: %f customer %d enters shop\\n", timestamp(), customer_num); if (customer_count > 1) { pthread_cond_wait(&Wait, &m); } if (flag_sleeping == 1) { pthread_cond_signal(&Barber); printf("DEBUG: %f barber wakes up\\n", timestamp()); } printf("DEBUG: %f customer %d starts haircut\\n",timestamp(),customer_num); pthread_cond_wait(&Done, &m); printf("DEBUG: %f customer %d leaves shop\\n",timestamp(),customer_num); customer_count--; pthread_cond_signal(&Wait); } sleep_exp(10.0,&m); } pthread_mutex_unlock(&m); } void *customer_thread(void *context) { int customer_num = (int)context; customer(customer_num); return 0; } void *barber_thread(void *context) { barber(); return 0; } void q2(void) { pthread_t t_customer[10]; pthread_t t_barber; int i; pthread_create(&t_barber,0,barber_thread, 0); for(i=0;i<10;i++) { pthread_create(&t_customer[i],0,customer_thread,(void* )i); } wait_until_done(); } void q3(void) { }
1
#include <pthread.h> struct handler_list { void (*handler)(void); struct handler_list * next; }; static pthread_mutex_t pthread_atfork_lock = PTHREAD_MUTEX_INITIALIZER; static struct handler_list * pthread_atfork_prepare = 0; static struct handler_list * pthread_atfork_parent = 0; static struct handler_list * pthread_atfork_child = 0; static void pthread_insert_list(struct handler_list ** list, void (*handler)(void), struct handler_list * newlist, int at_end) { if (handler == 0) return; if (at_end) { while(*list != 0) list = &((*list)->next); } newlist->handler = handler; newlist->next = *list; *list = newlist; } struct handler_list_block { struct handler_list prepare, parent, child; }; int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) { struct handler_list_block * block = (struct handler_list_block *) malloc(sizeof(struct handler_list_block)); if (block == 0) return ENOMEM; pthread_mutex_lock(&pthread_atfork_lock); pthread_insert_list(&pthread_atfork_prepare, prepare, &block->prepare, 0); pthread_insert_list(&pthread_atfork_parent, parent, &block->parent, 1); pthread_insert_list(&pthread_atfork_child, child, &block->child, 1); pthread_mutex_unlock(&pthread_atfork_lock); return 0; } static inline void pthread_call_handlers(struct handler_list * list) { for ( ; list != 0; list = list->next) (list->handler)(); } extern int __fork(void); int fork(void) { int pid; struct handler_list * prepare, * child, * parent; pthread_mutex_lock(&pthread_atfork_lock); prepare = pthread_atfork_prepare; child = pthread_atfork_child; parent = pthread_atfork_parent; pthread_mutex_unlock(&pthread_atfork_lock); pthread_call_handlers(prepare); pid = __fork(); if (pid == 0) { __pthread_reset_main_thread(); __fresetlockfiles(); pthread_call_handlers(child); } else { pthread_call_handlers(parent); } return pid; }
0
#include <pthread.h> int ca = 0; int ce = 0; int ci = 0; int co = 0; int cu = 0; int c; FILE * fp; pthread_t h[3]; pthread_mutex_t candl; pthread_mutex_t cande; int cuentaLineas(char * ptr); void contador(void * ptr); int main(int argc, char **argv){ char * nomarch; nomarch = argv[1]; fp = fopen(nomarch, "r"); if(fp == 0){ printf("no se pudo abrir el archivo %s\\n", nomarch); exit(1); } int lin = 0; lin = cuentaLineas(nomarch); int i; char buffer[200]; pthread_t h[3]; printf("lin %d\\n", lin); printf(" <lin>: %d\\n", lin); fflush(fp); pthread_mutex_init(&cande, 0); for(i = 0; i < 3; i++){ pthread_create(&h[i], 0, (void *) contador, &i); } for(i = 0; i < 3; i++){ pthread_join(h[i], 0); } printf("-- fin\\n"); fclose(fp); printf("totales: ca: %d, ce %d, ci %d, co %d, cu %d\\n", ca, ce, ci, co, cu); return 0; } void contador(void * ptr){ int id = (int) ptr; int aes = 0; int ees = 0; int ies = 0; int oes = 0; int ues = 0; c = fgetc(fp); while(!feof(fp) || c != '\\n'){ if(c == 'a' || c == 'A') aes++; else if(c == 'e' || c == 'e') ees++; else if(c == 'i' || c == 'I') ies++; else if(c == 'o' || c == 'O') oes++; else if(c == 'u' || c == 'U') ues++; else{ } c = fgetc(fp); } pthread_mutex_lock(&cande); ca = ca + aes; ce = ce + ees; ci = ci + ies; co = co + oes; cu = cu + ues; pthread_mutex_unlock(&cande); printf("Hilo: %d: ca: %2d, ce %2d, ci %2d, co %2d, cu %2d\\n", id, ca, ce, ci, co, cu); pthread_exit(&h[id]); } int cuentaLineas(char * ptr){ int i; char * nomarch; nomarch = ptr; fp = fopen(nomarch, "r"); while(!feof(fp)){ char c = getc(fp); if(c == '\\n') i++; } return (i); }
1
#include <pthread.h> pthread_mutex_t read_mutex, write_mutex; void* write() { char *ret; FILE *f; char str[20]; pthread_mutex_lock(&write_mutex); sleep(5); pthread_mutex_lock(&read_mutex); printf("\\nFile Locked. Please Enter the content to be written in the file...\\n"); scanf("%s", str); f = fopen("myFile.txt", "w"); fprintf(f, "%s\\n", str); fclose(f); pthread_mutex_unlock(&read_mutex); pthread_mutex_unlock(&write_mutex); printf("File Unlocked. File Can be read now.\\n"); return ret; } void* read() { char *ret; FILE *f; char str[20]; pthread_mutex_lock(&write_mutex); sleep(5); pthread_mutex_lock(&read_mutex); printf("Opening File.\\n"); f = fopen("myFile.txt", "r"); fscanf(f, "%s", str); printf("File content...\\n%s\\n", str); fclose(f); pthread_mutex_unlock(&write_mutex); pthread_mutex_unlock(&read_mutex); return ret; } int main() { pthread_t thread_t1, thread_t2; int ret; ret = pthread_create(&thread_t1, 0, &write, 0); ret = pthread_create(&thread_t2, 0, &read, 0); pthread_join(thread_t1, 0); pthread_join(thread_t2, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t stderr_lock = PTHREAD_MUTEX_INITIALIZER; static void (*die_cb)() = 0; static int suppress = s_none; void merr_suppress(int s) { suppress = s; } void die_set_cb(void (*cb)(int)) { die_cb = cb; } void fprintfp(FILE *fd, const char *fmt, ...) { va_list ap; __builtin_va_start((ap)); pthread_mutex_lock(&stderr_lock); vfprintf(fd, fmt, ap); pthread_mutex_unlock(&stderr_lock); ; } void die(int err, const char *fmt, ...) { va_list ap; __builtin_va_start((ap)); pthread_mutex_lock(&stderr_lock); fputs("die: ", stderr); vfprintf(stderr, fmt, ap); pthread_mutex_unlock(&stderr_lock); if (die_cb) die_cb(); ; exit(err); } void error(const char *fmt, ...) { va_list ap; if (suppress >= s_error) return; __builtin_va_start((ap)); pthread_mutex_lock(&stderr_lock); fputs("error: ", stderr); vfprintf(stderr, fmt, ap); pthread_mutex_unlock(&stderr_lock); ; } void warning(const char *fmt, ...) { va_list ap; if (suppress >= s_warning) return; __builtin_va_start((ap)); pthread_mutex_lock(&stderr_lock); fputs("warning: ", stderr); vfprintf(stderr, fmt, ap); pthread_mutex_unlock(&stderr_lock); ; } void info(const char *fmt, ...) { va_list ap; if (suppress >= s_info) return; __builtin_va_start((ap)); pthread_mutex_lock(&stderr_lock); fputs("info: ", stderr); vfprintf(stderr, fmt, ap); pthread_mutex_unlock(&stderr_lock); ; }
1
#include <pthread.h> float pougre=0; pthread_mutex_t lemutex; void* oddsum(void* arg) { int plo; for (plo=1 ; plo<=100 ; plo+=2) { pthread_mutex_lock(&lemutex); pougre+=sqrt(plo); pthread_mutex_unlock(&lemutex); } pthread_exit(0); } void* evensum(void* arg) { int iougre; for (iougre=0 ; iougre<=100 ; iougre+=2) { pthread_mutex_lock(&lemutex); pougre+=sqrt(iougre); pthread_mutex_unlock(&lemutex); } pthread_exit(0); } int main(int argc, char** argv) { pthread_t odd, even; pthread_mutex_init (&lemutex, 0) ; if (pthread_create(&odd, 0, oddsum, 0) != 0) { perror("Erreur pendant la création du thread impair"); exit (1); } if (pthread_create(&even, 0, evensum, 0) != 0) { perror("Erreur pendant la création du thread pair"); exit (1); } if (pthread_join(odd, 0) == -1) { perror("Erreur pthread_join"); exit(1); } if (pthread_join(even, 0) == -1) { perror("Erreur pthread_join"); exit(1); } printf("Somme des racines de 1 à 100 = %f", pougre); return 0; }
0
#include <pthread.h> int tid; pthread_mutex_t * p2c; pthread_mutex_t * c2p; int numVerts; int numThr; int** M_prev; int** M_curr; } pt_mat; void *Thr(void *thrargs) { struct pt_mat *mat; mat = (struct pt_mat *)thrargs; int t = (mat->tid); int i,j,k; for(k=0; k<(mat->numVerts); k++) { pthread_mutex_lock( &(mat->p2c[t]) ); for (i = t; i < (mat->numVerts); i+=(mat->numThr)) { for(j = 0; j < (mat->numVerts); j++) { if ( ( (mat->M_prev[k][j])==1 && (mat->M_prev[i][k]) ) || (mat->M_prev[i][j])==1 ) (mat->M_curr[i][j]) = 1; } } pthread_mutex_unlock(&(mat->c2p[t])); } pthread_exit (0) ; } int wtc_thr(int nThr, int nVerts, int** matrix) { struct timeval startt, endt; gettimeofday(&startt, 0 ); pthread_t* thra = (pthread_t*)malloc(sizeof(pthread_t)*nThr); int i,j; pt_mat** matsrc = (pt_mat**)malloc(sizeof(pt_mat*)*nThr); for(i=0; i<nThr; i++){ matsrc[i] = (pt_mat*)malloc(sizeof(pt_mat));; } int** cmatrix = (int**)malloc(nVerts*sizeof(int*)); for(i=0; i<nVerts; i++){ cmatrix[i] = (int*)malloc(nVerts*sizeof(int)); for(j = 0; j<nVerts; j++){ cmatrix[i][j]=0; } } pthread_mutex_t * p2c = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*nThr); pthread_mutex_t * c2p = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*nThr); int k; for(k=0; k<nThr; k++) { pthread_mutex_init(&p2c[k], 0); pthread_mutex_init(&c2p[k], 0); pthread_mutex_lock(&p2c[k]); pthread_mutex_lock(&c2p[k]); } int rc; for (k=0; k<nThr; k++) { matsrc[k]->tid = k; matsrc[k]->M_prev = matrix; matsrc[k]->M_curr = cmatrix; matsrc[k]->numVerts = nVerts; matsrc[k]->numThr = nThr; matsrc[k]->p2c = p2c; matsrc[k]->c2p = c2p; rc = pthread_create(&thra[k], 0, Thr, (void *)matsrc[k]) ; if( rc ) { exit( -1 ); } } int m,y,z; for (m=0; m<nVerts;m++) { for(k=0;k<nThr;k++){pthread_mutex_unlock(&p2c[k]);} for(k=0;k<nThr;k++){ pthread_mutex_lock(&c2p[k]); } for(y=0; y<nVerts; y++) { for(z=0; z<nVerts; z++) { matrix[y][z]=cmatrix[y][z]; } } } for (k=0; k<nThr; k++) { pthread_join( thra[k], 0 ); pthread_mutex_destroy(&p2c[k]); pthread_mutex_destroy(&c2p[k]); } free(c2p); free(p2c); free(thra); for(i=0; i<nThr; i++){ free(matsrc[i]); } free(matsrc); for(i=0; i<nVerts; i++){ free(cmatrix[i]); } free(cmatrix); printf("Output:\\n"); printMatrix(matrix, nVerts); gettimeofday(&endt, 0); int elapsedTime; elapsedTime = (endt.tv_usec - startt.tv_usec); return 0; }
1
#include <pthread.h> void ft_print_maps_size(void) { ft_putstr("\\033[33m"); ft_putstr("Tiny size: "); ft_putnbr(g_env.tiny_size); ft_putstr(" || alloc: "); ft_putnbr(g_env.tiny_alloc_size); ft_putchar('\\n'); ft_putstr("Small size: "); ft_putnbr(g_env.small_size); ft_putstr(" || alloc: "); ft_putnbr(g_env.small_alloc_size); ft_putchar('\\n'); ft_putstr("Header map : "); ft_putnbr(sizeof(t_zone)); ft_putstr("\\nHeader block : "); ft_putnbr(sizeof(t_block)); ft_putchar('\\n'); ft_putstr("\\033[0m"); } void show_alloc_mem_verbose(void) { pthread_mutex_lock(&g_mutex); ft_print_maps_size(); print_zone(g_env.tiny, "TINY", 1); print_zone(g_env.small, "SMALL", 1); print_zone(g_env.large, "LARGE", 1); print_total(); pthread_mutex_unlock(&g_mutex); }
0
#include <pthread.h> pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexB = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexC = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexD = PTHREAD_MUTEX_INITIALIZER; void *thread_func1(void *tmp) { while(1) { pthread_mutex_lock(&mutexA); printf("A"); pthread_mutex_unlock(&mutexB); } return 0; } void *thread_func2(void *tmp) { while(1) { pthread_mutex_lock(&mutexB); printf("B"); pthread_mutex_unlock(&mutexC); } return 0; } void *thread_func3(void *tmp) { while(1) { pthread_mutex_lock(&mutexC); printf("C"); pthread_mutex_unlock(&mutexD); } return 0; } void *thread_func4(void *tmp) { while(1) { pthread_mutex_lock(&mutexD); printf("D"); pthread_mutex_unlock(&mutexA); } return 0; } int main(void) { pthread_mutex_lock(&mutexB); pthread_mutex_lock(&mutexC); pthread_mutex_lock(&mutexD); int ret; pthread_t pid1, pid2, pid3, pid4; ret = pthread_create(&pid1, 0, thread_func1, 0); if(ret < 0) err_sys("pthread_create error"); ret = pthread_create(&pid2, 0, thread_func2, 0); if(ret < 0) err_sys("pthread_create error"); ret = pthread_create(&pid3, 0, thread_func3, 0); if(ret < 0) err_sys("pthread_create error"); ret = pthread_create(&pid4, 0, thread_func4, 0); if(ret < 0) err_sys("pthread_create error"); alarm(5); pthread_join(pid1, 0); pthread_join(pid2, 0); pthread_join(pid3, 0); pthread_join(pid4, 0); return 0; }
1
#include <pthread.h> int counter = 0; pthread_mutex_t my_mutex[5]; pthread_mutex_t my_cond_mutex; pthread_cond_t cond; void *test_mutex(void *tid) { int thread_id; int rnd; int *tt; tt = tid; thread_id = (int) *tt; rnd = rand() % 3; sleep(rnd); pthread_mutex_lock(&my_cond_mutex); pthread_cond_wait( &cond, &my_cond_mutex); pthread_mutex_unlock(&my_cond_mutex); counter = counter + thread_id; thread_id, counter); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t thread1[5]; int t; int ec; int thread_ids[5]; srand(time(0)); pthread_mutex_init(&my_cond_mutex, 0); pthread_cond_init(&cond,0); for(t=0;t<5;t++){ thread_ids[t] = t; printf("In main: creating thread %d\\n", t); ec = pthread_create(&thread1[t], 0, test_mutex, (void *)&thread_ids[t]); } sleep(4); pthread_cond_broadcast(&cond); printf( "the results is %d \\n",counter); pthread_exit(0); }
0
#include <pthread.h> unsigned long Flag_Count; unsigned long Flag_Range; unsigned long Flag_Threads; unsigned long Threads_Completed; pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t Job_Done = PTHREAD_COND_INITIALIZER; void emit_help(void); void *worker(void *unused); int main(int argc, char *argv[]) { int ch; pthread_t *tids; struct timespec wait; jkiss64_init(0); setvbuf(stdout, (char *) 0, _IOLBF, (size_t) 0); while ((ch = getopt(argc, argv, "h?c:R:t:")) != -1) { switch (ch) { case 'c': Flag_Count = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 'R': Flag_Range = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 't': Flag_Threads = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 'h': case '?': default: emit_help(); } } argc -= optind; argv += optind; if (Flag_Count == 0 || Flag_Range == 0 || Flag_Threads == 0) emit_help(); if ((tids = calloc(sizeof(pthread_t), (size_t) Flag_Threads)) == 0) err(EX_OSERR, "could not calloc() threads list"); for (unsigned int i = 0; i < Flag_Threads; i++) { if (pthread_create(&tids[i], 0, worker, 0) != 0) err(EX_OSERR, "could not pthread_create() thread %d", i); } wait.tv_sec = 1; wait.tv_nsec = 63; for (;;) { pthread_mutex_lock(&Lock); if (Threads_Completed == Flag_Threads) break; pthread_cond_timedwait(&Job_Done, &Lock, &wait); pthread_mutex_unlock(&Lock); } exit(0); } void emit_help(void) { fprintf(stderr, "Usage: ./bias -c count -R range -t threads\\n"); exit(EX_USAGE); } void *worker(void *unused) { jkiss64_init_thread(); for (unsigned long i = 0; i < Flag_Count; i++) printf("%llu\\n", jkiss64_rand() % Flag_Range); pthread_mutex_lock(&Lock); Threads_Completed++; pthread_mutex_unlock(&Lock); pthread_cond_signal(&Job_Done); return (void *) 0; }
1
#include <pthread.h> extern struct FileList* root; void* upload(void* arg) { int clntSock = ((struct connection*)arg)->clntSock; struct sockaddr_in clntAddr = ((struct connection*)arg)->clntAddr; int clntAddrLen = ((struct connection*)arg)->clntAddrLen; struct FileList* file; char buffer[MAXLEN + 9]; int bufferLen; pthread_detach(pthread_self()); free(arg); getMsg(clntSock, buffer, &bufferLen); if(buffer[0] == 0x06) { unsigned char file_name_length; char file_name[256]; file_name_length = buffer[5]; memcpy(file_name, buffer + 6, file_name_length); file_name[file_name_length] = 0; file = findFile(root, file_name); if(file) putMsg(clntSock, buffer, bufferLen); else { close(clntSock); return 0; } } else { close(clntSock); return 0; } getMsg(clntSock, buffer, &bufferLen); if(buffer[0] == 0x07) { char* bitmap = (char*)malloc((file->file_size + MAXLEN) / MAXLEN); memcpy(bitmap, buffer + 5, (file->file_size + MAXLEN) / MAXLEN); updatePeer(file, clntAddr.sin_addr.s_addr, bitmap); free(bitmap); memcpy(buffer + 5, file->bitmap, (file->file_size + MAXLEN) / MAXLEN); putMsg(clntSock, buffer, bufferLen); } else { close(clntSock); return 0; } getMsg(clntSock, buffer, &bufferLen); if(buffer[0] == 0x08) { unsigned int piece; FILE* fp; memcpy(&piece, buffer + 5, 4); piece = ntohl(piece); buffer[0] = 0x09; pthread_mutex_lock(&(file->mutex)); fp = fopen(file->file_name, "rb"); fseek(fp, MAXLEN * (piece - 1), 0); bufferLen = fread(buffer + 9, 1, MAXLEN, fp) + 9; fclose(fp); pthread_mutex_unlock(&(file->mutex)); putMsg(clntSock, buffer, bufferLen); } else { close(clntSock); return 0; } return 0; } void* seeder(void* arg) { int clntSock; struct sockaddr_in clntAddr; int clntAddrLen; int servSock; struct sockaddr_in servAddr; int servAddrLen; int so_reuseaddr = 1; if((servSock = socket(PF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "socket create error\\n"); return 0; } servAddrLen = sizeof(servAddr); memset(&servAddr, 0, servAddrLen); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons((unsigned short)9001); setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr, sizeof(so_reuseaddr)); if(bind(servSock, (struct sockaddr*)&servAddr, servAddrLen)) { fprintf(stderr, "bind error\\n"); close(servSock); return 0; } if(listen(servSock, 1000)) { fprintf(stderr, "listen error\\n"); return 0; } while(1) { pthread_t t; struct connection* c; clntAddrLen = sizeof(clntAddr); if((clntSock = accept(servSock, (struct sockaddr*)&clntAddr, &clntAddrLen)) < 0) { fprintf(stderr, "accept error\\n"); close(servSock); return 0; } c = (struct connection*)malloc(sizeof(struct connection)); c->clntSock = clntSock; c->clntAddr = clntAddr; c->clntAddrLen = clntAddrLen; if(pthread_create(&t, 0, upload, (void*)c)) { fprintf(stderr, "thread create error\\n"); close(clntSock); close(servSock); free(c); return 0; } } }
0
#include <pthread.h> pthread_mutex_t lock; int pid_map[350 +1]; int last; int allocate_map(void) { int i; for (i = 300; i < 350 +1; i++) pid_map[i] = 0; last = 300; return 1; } int allocate_pid(void) { int new_pid, i; int map_range = (350 - 300); if (last > 350 || last < 300) new_pid = 300; else new_pid = last; pthread_mutex_lock(&lock); for(i = 0; (i < map_range) && (pid_map[new_pid] != 0); i++){ new_pid++; if(new_pid < 300 || new_pid > 350) new_pid = 300; } if(!(i < map_range)) new_pid = -1; else { last = new_pid; pid_map[new_pid] = 1; } if(new_pid != -1) printf("Tread acquired pid %d.\\n", new_pid); pthread_mutex_unlock(&lock); return new_pid; } void release_pid(int pid) { pthread_mutex_lock(&lock); printf("Tread releasing pid %d.\\n", pid); pid_map[pid] = 0; pthread_mutex_unlock(&lock); return; } int random_num_gen(){ int random_number; time_t t; random_number = (int)(rand() % 5 + 1); return random_number; } void *allocator(void *param) { int thread_num = *(int *)param + 1; int pid, i; for(i = 0; i < 10; i++){ pid = allocate_pid(); int rn = random_num_gen(); sleep(rn); if(pid != -1){ release_pid(pid); } } pthread_exit(0); } int main(void) { int i; pthread_t tids[100]; if (allocate_map() == -1) return -1; if(pthread_mutex_init(&lock, 0) != 0){ printf("Failure to initialize lock."); return 1; } for(i = 0; i < 100; i++) if(pthread_create(&tids[i], 0, allocator, &i)){ printf("Error creating thread %d", i); return 1; } for (i = 0; i < 100; i++) if(pthread_join(tids[i], 0)){ printf("Error joining thread.\\n"); return 1; } printf("***DONE***\\n"); return 0; }
1
#include <pthread.h> struct signalfd_context { int fd; int flags; struct signalfd_context *next; }; static struct signalfd_context *signalfd_contexts; pthread_mutex_t signalfd_context_mtx = PTHREAD_MUTEX_INITIALIZER; struct signalfd_context * get_signalfd_context(int fd, bool create_new) { for (struct signalfd_context *ctx = signalfd_contexts; ctx; ctx = ctx->next) { if (fd == ctx->fd) { return ctx; } } if (create_new) { struct signalfd_context *new_ctx = calloc(1, sizeof(struct signalfd_context)); if (!new_ctx) { return 0; } new_ctx->fd = -1; new_ctx->next = signalfd_contexts; signalfd_contexts = new_ctx; return new_ctx; } return 0; } static int signalfd_impl(int fd, const sigset_t *sigs, int flags) { if (fd != -1) { errno = EINVAL; return -1; } if (flags & ~(SFD_NONBLOCK | SFD_CLOEXEC)) { errno = EINVAL; return -1; } struct signalfd_context *ctx = get_signalfd_context(-1, 1); if (!ctx) { errno = EMFILE; return -1; } ctx->fd = kqueue(); if (ctx->fd == -1) { return -1; } ctx->flags = flags; struct kevent kevs[_SIG_MAXSIG]; int n = 0; for (int i = 1; i <= _SIG_MAXSIG; ++i) { if (sigismember(sigs, i)) { EV_SET(&kevs[n++], i, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); } } int ret = kevent(ctx->fd, kevs, n, 0, 0, 0); if (ret == -1) { close(ctx->fd); ctx->fd = -1; return -1; } return ctx->fd; } int signalfd(int fd, const sigset_t *sigs, int flags) { pthread_mutex_lock(&signalfd_context_mtx); int ret = signalfd_impl(fd, sigs, flags); pthread_mutex_unlock(&signalfd_context_mtx); return ret; } ssize_t signalfd_read(struct signalfd_context *ctx, void *buf, size_t nbytes) { int fd = ctx->fd; int flags = ctx->flags; pthread_mutex_unlock(&signalfd_context_mtx); if (nbytes != sizeof(struct signalfd_siginfo)) { errno = EINVAL; return -1; } struct timespec timeout = {0, 0}; struct kevent kev; int ret = kevent( fd, 0, 0, &kev, 1, (flags & SFD_NONBLOCK) ? &timeout : 0); if (ret == -1) { return -1; } else if (ret == 0) { errno = EAGAIN; return -1; } memset(buf, '\\0', nbytes); struct signalfd_siginfo *sig_buf = buf; sig_buf->ssi_signo = (uint32_t)kev.ident; return (ssize_t)nbytes; } int signalfd_close(struct signalfd_context *ctx) { int ret = close(ctx->fd); ctx->fd = -1; return ret; }
0
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; int i = 0; while(i < 3) { pthread_mutex_unlock(&(sip->lock)); printf("Value is currently: %i\\n", sip->value); pthread_mutex_lock(&(sip->lock)); i++; } pthread_mutex_unlock(&(sip->lock)); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); return sip->value-2; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(800)]; 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==(800)) { 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<(800); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(800); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(800); 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> pthread_mutex_t *mut; int writers; int readers; int waiting; pthread_cond_t *writeOK, *readOK; } rwl; rwl *initlock (void); void readlock (rwl *lock, int d); void writelock (rwl *lock, int d); void readunlock (rwl *lock); void writeunlock (rwl *lock); void deletelock (rwl *lock); rwl *lock; int id; long delay; } rwargs; rwargs *newRWargs (rwl *l, int i, long d); void *reader (void *args); void *writer (void *args); static int data = 1; int main () { pthread_t r1, r2, r3, r4, w1; rwargs *a1, *a2, *a3, *a4, *a5; rwl *lock; lock = initlock (); a1 = newRWargs (lock, 1, 150000); pthread_create (&w1, 0, writer, a1); a2 = newRWargs (lock, 1, 50000); pthread_create (&r1, 0, reader, a2); a3 = newRWargs (lock, 2, 100000); pthread_create (&r2, 0, reader, a3); a4 = newRWargs (lock, 3, 400000); pthread_create (&r3, 0, reader, a4); a5 = newRWargs (lock, 4, 800000); pthread_create (&r4, 0, reader, a5); pthread_join (w1, 0); pthread_join (r1, 0); pthread_join (r2, 0); pthread_join (r3, 0); pthread_join (r4, 0); free (a1); free (a2); free (a3); free (a4); free (a5); return 0; } rwargs *newRWargs (rwl *l, int i, long d) { rwargs *args; args = (rwargs *)malloc (sizeof (rwargs)); if (args == 0) return (0); args->lock = l; args->id = i; args->delay = d; return (args); } void *reader (void *args) { rwargs *a; int d; a = (rwargs *)args; do { readlock (a->lock, a->id); d = data; usleep (a->delay); readunlock (a->lock); printf ("Reader %d : Data = %d\\n", a->id, d); usleep (a->delay); } while (d != 0); printf ("Reader %d: Finished.\\n", a->id); return (0); } void *writer (void *args) { rwargs *a; int i; a = (rwargs *)args; for (i = 2; i < 5; i++) { writelock (a->lock, a->id); data = i; usleep (a->delay); writeunlock (a->lock); printf ("Writer %d: Wrote %d\\n", a->id, i); usleep (a->delay); } printf ("Writer %d: Finishing...\\n", a->id); writelock (a->lock, a->id); data = 0; writeunlock (a->lock); printf ("Writer %d: Finished.\\n", a->id); return (0); } rwl *initlock (void) { rwl *lock; lock = (rwl *)malloc (sizeof (rwl)); if (lock == 0) return (0); lock->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); if (lock->mut == 0) { free (lock); return (0); } lock->writeOK = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); if (lock->writeOK == 0) { free (lock->mut); free (lock); return (0); } lock->readOK = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); if (lock->writeOK == 0) { free (lock->mut); free (lock->writeOK); free (lock); return (0); } pthread_mutex_init (lock->mut, 0); pthread_cond_init (lock->writeOK, 0); pthread_cond_init (lock->readOK, 0); lock->readers = 0; lock->writers = 0; lock->waiting = 0; return (lock); } void readlock (rwl *lock, int d) { pthread_mutex_lock (lock->mut); if (lock->writers || lock->waiting) { do { printf ("reader %d blocked.\\n", d); pthread_cond_wait (lock->readOK, lock->mut); printf ("reader %d unblocked.\\n", d); } while (lock->writers); } lock->readers++; pthread_mutex_unlock (lock->mut); return; } void writelock (rwl *lock, int d) { pthread_mutex_lock (lock->mut); lock->waiting++; while (lock->readers || lock->writers) { printf ("writer %d blocked.\\n", d); pthread_cond_wait (lock->writeOK, lock->mut); printf ("writer %d unblocked.\\n", d); } lock->waiting--; lock->writers++; pthread_mutex_unlock (lock->mut); return; } void readunlock (rwl *lock) { pthread_mutex_lock (lock->mut); lock->readers--; pthread_cond_signal (lock->writeOK); pthread_mutex_unlock (lock->mut); } void writeunlock (rwl *lock) { pthread_mutex_lock (lock->mut); lock->writers--; pthread_cond_broadcast (lock->readOK); pthread_mutex_unlock (lock->mut); } void deletelock (rwl *lock) { pthread_mutex_destroy (lock->mut); pthread_cond_destroy (lock->readOK); pthread_cond_destroy (lock->writeOK); free (lock); return; }
1
#include <pthread.h> int create_cyclic_int_buffer(struct cyclic_int_buffer *cyclic_buffer, size_t capacity) { cyclic_buffer->internal_capacity = capacity + 1; cyclic_buffer->read_idx = 0; cyclic_buffer->write_idx = 0; cyclic_buffer->is_empty = 1; cyclic_buffer->is_full = 0; pthread_mutex_init(&(cyclic_buffer->read_mutex), 0); pthread_mutex_init(&(cyclic_buffer->write_mutex), 0); pthread_mutex_init(&(cyclic_buffer->empty_read_mutex), 0); pthread_mutex_init(&(cyclic_buffer->full_write_mutex), 0); pthread_mutex_lock(&(cyclic_buffer->empty_read_mutex)); cyclic_buffer->data = (int *) malloc(cyclic_buffer->internal_capacity * sizeof(int)); return 0; } size_t get_cyclic_buffer_size(struct cyclic_int_buffer *cyclic_buffer) { int read_idx = cyclic_buffer->read_idx; int write_idx = cyclic_buffer->write_idx; int size = write_idx - read_idx; if (size < 0) { size += cyclic_buffer->internal_capacity; } return (size_t) size; } size_t get_cyclic_buffer_capacity(struct cyclic_int_buffer *cyclic_buffer) { return cyclic_buffer->internal_capacity - 1; } int get_element_from_cyclic_buffer(struct cyclic_int_buffer *cyclic_buffer, size_t index, int *result) { int retval = 0; *result = 0; pthread_mutex_lock(&(cyclic_buffer->read_mutex)); int read_idx = cyclic_buffer->read_idx; int write_idx = cyclic_buffer->write_idx; if (read_idx == write_idx) { retval = BUFFER_IS_EMPTY; } else if (read_idx < write_idx) { if (read_idx <= index && index < write_idx) { *result = cyclic_buffer->data[index]; } else { retval = INDEX_OUT_OF_RANGE; } } else { if (0 <= index && index < write_idx || read_idx <= index && index < cyclic_buffer->internal_capacity) { *result = cyclic_buffer->data[index]; } else { retval = INDEX_OUT_OF_RANGE; } } pthread_mutex_unlock(&(cyclic_buffer->read_mutex)); return retval; } int put(struct cyclic_int_buffer *cyclic_buffer, int value) { pthread_mutex_lock(&(cyclic_buffer->full_write_mutex)); pthread_mutex_lock(&(cyclic_buffer->write_mutex)); int write_idx = cyclic_buffer->write_idx; cyclic_buffer->data[write_idx] = value; write_idx++; write_idx %= cyclic_buffer->internal_capacity; cyclic_buffer->write_idx = write_idx; size_t size = get_cyclic_buffer_size(cyclic_buffer); cyclic_buffer->is_full = (size == cyclic_buffer->internal_capacity-1); if (! cyclic_buffer->is_full) { pthread_mutex_unlock(&(cyclic_buffer->full_write_mutex)); } if (cyclic_buffer->is_empty) { cyclic_buffer->is_empty = 0; pthread_mutex_unlock(&(cyclic_buffer->empty_read_mutex)); } pthread_mutex_unlock(&(cyclic_buffer->write_mutex)); return 0; } int get(struct cyclic_int_buffer *cyclic_buffer) { pthread_mutex_lock(&(cyclic_buffer->empty_read_mutex)); pthread_mutex_lock(&(cyclic_buffer->read_mutex)); int read_idx = cyclic_buffer->read_idx; int result = cyclic_buffer->data[read_idx]; read_idx++; read_idx %= cyclic_buffer->internal_capacity; cyclic_buffer->read_idx = read_idx; size_t size = get_cyclic_buffer_size(cyclic_buffer); cyclic_buffer->is_empty = (size == 0); if (! cyclic_buffer->is_empty) { pthread_mutex_unlock(&(cyclic_buffer->empty_read_mutex)); } if (cyclic_buffer->is_full) { cyclic_buffer->is_full = 0; pthread_mutex_unlock(&(cyclic_buffer->full_write_mutex)); } pthread_mutex_unlock(&(cyclic_buffer->read_mutex)); return result; } int delete_cyclic_buffer(struct cyclic_int_buffer *cyclic_buffer) { pthread_mutex_destroy(&(cyclic_buffer->read_mutex)); pthread_mutex_destroy(&(cyclic_buffer->write_mutex)); pthread_mutex_destroy(&(cyclic_buffer->empty_read_mutex)); pthread_mutex_destroy(&(cyclic_buffer->full_write_mutex)); free(cyclic_buffer->data); cyclic_buffer->data = 0; return 0; } int print_cyclic_buffer(struct cyclic_int_buffer *cyclic_buffer, FILE *output) { int idx = cyclic_buffer->read_idx; int size = get_cyclic_buffer_size(cyclic_buffer); fprintf(output, "["); for (int i = 0; i < size; i++) { if (i > 0) { fprintf(output, ", "); } int val = cyclic_buffer->data[idx]; idx++; idx %= cyclic_buffer->internal_capacity; fprintf(output, "%d=>%d", idx, val); } fprintf(output, "]\\n"); }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo *foo_alloc(int id) { struct foo *fp; int idx; if((fp = (struct foo *)malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); ++fp->f_count; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if(fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count != 1) { --fp->f_count; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; } else { while(tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { --fp->f_count; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> struct mpd_connection *conn = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void InitMPC(void) { FILE * pFile; pFile = fopen (ONLINE_LIST_PATH,"wb"); if (pFile==0) { perror ("nd InitMPC create online.lst.m3u Error\\n"); } fclose(pFile); new_connection(&conn); } int new_connection(struct mpd_connection **conn) { *conn = mpd_connection_new(0, 0, 30000); if (*conn == 0) { printf("nd new_connection %s\\n", "Out of memory"); return -1; } if (mpd_connection_get_error(*conn) != MPD_ERROR_SUCCESS) { printf("nd new_connection %s\\n", mpd_connection_get_error_message(*conn)); mpd_connection_free(*conn); *conn = 0; return -1; } return 0; } void my_mpd_run_pause(void) { struct mpd_status *status = 0; pthread_mutex_lock(&mutex); status = mpd_run_status(conn); if (!status) { printf("nd my_mpd_run_pause mpd_run_status1 %s \\n", mpd_connection_get_error_message(conn)); } else { if (mpd_status_get_state(status) == MPD_STATE_PLAY) { mpd_run_pause(conn, 1); } mpd_status_free(status); } pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> char share_buffer[5]; int curr=-1; int empty=0; int full=5; pthread_mutex_t share_mutex; sem_t non_empty,non_full; void * consumer_func(void * whichone) { int position; char data; char *who; who = (char *)whichone; printf("%s: Starting...\\n",who); while(1) { sem_wait(&non_empty); pthread_mutex_lock(&share_mutex); data = share_buffer[curr]; position = curr--; printf ("%s: Reading [%c] from buffer at position %d\\n", who, data, position); sem_post(&non_full); pthread_mutex_unlock(&share_mutex); sleep(1); } return 0; } void * producer_func(void * whichone) { int position; char data; char * who; who=(char *)whichone; printf("%s:Starting...\\n",who); while(1) { srand((unsigned int)time(0)); data = (char)(rand()%(90 -65 +1)+65); sem_wait(&non_full); pthread_mutex_lock(&share_mutex); position = ++curr; share_buffer[curr]=data; printf("%s:Writing[%c] to buffer at position %d\\n",who,data,position); sem_post(&non_empty); pthread_mutex_unlock(&share_mutex); sleep(1); } return 0; } int main(void) { pthread_t c1,c2,p1,p2; pthread_mutex_init(&share_mutex,0); sem_init(&non_empty,0,empty); sem_init(&non_full,0,full); pthread_create(&c1,0,&consumer_func,"consumer1"); pthread_create(&c2,0,&consumer_func,"consumer2"); pthread_create(&p1,0,&producer_func,"producer1"); pthread_create(&p2,0,&producer_func,"producer2"); pthread_join(c1,0); pthread_join(c2,0); pthread_join(p1,0); pthread_join(p2,0); sem_destroy(&non_empty); sem_destroy(&non_full); pthread_mutex_destroy(&share_mutex); return 0; }
1
#include <pthread.h> static pthread_mutex_t *lockarray; static void lock_callback(int mode, int type, char* file, int line) { (void) file; (void) line; if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&(lockarray[type])); } else { pthread_mutex_unlock(&(lockarray[type])); } } static unsigned long thread_id() { return (unsigned long) pthread_self(); } void init_locks() { lockarray = (pthread_mutex_t *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); int i; for (i = 0; i < CRYPTO_num_locks(); i++) { pthread_mutex_init(&(lockarray[i]), 0); } CRYPTO_set_id_callback((unsigned long (*)()) thread_id); CRYPTO_set_locking_callback((void (*)()) lock_callback); } void kill_locks() { CRYPTO_set_locking_callback(0); int i; for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(lockarray[i])); OPENSSL_free(lockarray); }
0
#include <pthread.h> static char pool[5 * STRING_SIZE]; static int inUse[5]; static unsigned int inUseCount; static pthread_mutex_t mutex; static pthread_cond_t condition; int initStringPool() { int i, ret; pthread_mutexattr_t attr; inUseCount = 0; ret = initRTMutexAttr(&attr); if(ret != 0) { PRINT_ERR("Failed to int rt mutex attributes (%d).\\n", ret); return ret; } ret = pthread_mutex_init(&mutex, &attr); if(ret != 0) { PRINT_ERR("Failed to int mutex (%d).\\n", ret); return ret; } ret = pthread_cond_init(&condition, 0); if(ret != 0) { PRINT_ERR("Failed to int condition variable (%d).\\n", ret); return ret; } for(i = 0; i < 5; ++i) inUse[i] = 0; pthread_mutexattr_destroy(&attr); return 0; } int destroyStringPool() { int ret; ret = pthread_cond_destroy(&condition); if(ret != 0) { PRINT_ERR("Failed to destroy condition variable (%d).\\n", ret); return ret; } ret = pthread_mutex_destroy(&mutex); if(ret != 0) { PRINT_ERR("Failed to destroy mutex (%d).\\n", ret); return ret; } return 0; } char* reserveString() { pthread_mutex_lock(&mutex); while(inUseCount >= 5) pthread_cond_wait(&condition, &mutex); int i; char *result; for(i = 0; i < 5; ++i) { if(!inUse[i]) { result = pool + (i * STRING_SIZE); inUse[i] = 1; ++inUseCount; break; } } pthread_mutex_unlock(&mutex); return result; } void releaseString(char *p_string) { pthread_mutex_lock(&mutex); if(inUseCount != 0) { int i; for(i = 0; i < 5; ++i) { if(p_string == (pool + (i * STRING_SIZE))) { inUse[i] = 0; --inUseCount; break; } } } pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition); }
1
#include <pthread.h> void *iniciarAplicacao() { int i; ic_num = 0; for (i = 0; i < MAX_PS; i++) ps[i] = -1; int te, tr; pthread_t threadReceberPacotes; tr = pthread_create(&threadReceberPacotes, 0, receberPacotes, 0); if (tr) { printf("ERRO: impossivel criar a thread : receberPacotes\\n"); exit(-1); } pthread_join(threadReceberPacotes, 0); } void *receberPacotes() { while (TRUE) { struct pacote pacote_rcv; pthread_mutex_lock(&mutex_apli_trans_rcv2); if (buffer_apli_trans_rcv.tam_buffer != -1) { retirarPacotesBufferApliTransRcv(&pacote_rcv); if (strlen(pacote_rcv.buffer) >= pacote_rcv.tam_buffer) { printf("[APLIC - RCV] Tam_buffer: '%d' Bytes\\n", pacote_rcv.tam_buffer); printf("[APLIC - RCV] Buffer: '%s'\\n", pacote_rcv.buffer); } } pthread_mutex_unlock(&mutex_apli_trans_rcv1); } } int aps() { int i; for (i = 0; i < MAX_PS; ++i) { if (ps[i] == -1) { ps[i] = 1; return i; } } return -1; } int fps(int num_ps) { ps[num_ps] = -1; printf("[APLIC - FPS]Recebi pedido de fechamento do ps '%d'\\n", num_ps); return 1; } struct ic conectar(int env_no, int num_ps) { struct ic ic; int i; int flag_existe = 0; struct pacote pacote_env; printf("[APLIC - CON]Recebi pedido para conectar no no : '%d', ps '%d'\\n", env_no, num_ps); for (i = 0; i < MAX_PS; i++) if (ps[num_ps] == 1) flag_existe = 1; if (flag_existe == 1) { pthread_mutex_lock(&mutex_apli_trans_env1); pacote_env.tipo = CONECTAR; ic.num = ic_num; ic.env_no = env_no; ic.ps = num_ps; ic.num_no = file_info.num_no; ic_num++; colocarPacotesBufferApliTransEnv(pacote_env, ic); pthread_mutex_unlock(&mutex_apli_trans_env2); pthread_mutex_lock(&mutex_apli_trans_env1); retornoTransporte(pacote_env); pthread_mutex_unlock(&mutex_apli_trans_env1); ic.end_buffer = buffer_apli_trans_env.retorno; return ic; } else { ic.env_no = -1; return ic; } } int desconectar(struct ic ic) { struct pacote pacote_env; printf("[APLIC - DESC]Recebi pedido para desconectar do env_no: '%d' e ps: '%d'\\n", ic.env_no, ic.ps); pthread_mutex_lock(&mutex_apli_trans_env1); pacote_env.tipo = DESCONECTAR; colocarPacotesBufferApliTransEnv(pacote_env, ic); pthread_mutex_unlock(&mutex_apli_trans_env2); pthread_mutex_lock(&mutex_apli_trans_env1); retornoTransporte(pacote_env); pthread_mutex_unlock(&mutex_apli_trans_env1); return 1; } void baixar(struct ic ic, char *arq) { struct pacote pacote_env; printf("[APLIC - BAIXAR] Data: '%s'\\n", arq); printf("[APLIC - BAIXAR] Tam_buffer: '%zd'\\n", strlen(arq)); pthread_mutex_lock(&mutex_apli_trans_env1); pacote_env.tipo = DADOS; pacote_env.tam_buffer = strlen(arq); strncpy(pacote_env.buffer, arq, strlen(arq)); pacote_env.buffer[strlen(arq) + 1] = '\\0'; colocarPacotesBufferApliTransEnv(pacote_env, ic); pthread_mutex_unlock(&mutex_apli_trans_env2); } void colocarPacotesBufferApliTransEnv(struct pacote pacote, struct ic ic) { buffer_apli_trans_env.tam_buffer = pacote.tam_buffer; buffer_apli_trans_env.tipo = pacote.tipo; memcpy(&buffer_apli_trans_env.ic, &ic, sizeof (ic)); memcpy(&buffer_apli_trans_env.data, &pacote, sizeof (pacote)); } void retirarPacotesBufferApliTransRcv(struct pacote *pacote) { pacote->tam_buffer = buffer_apli_trans_rcv.data.tam_buffer; strcpy(pacote->buffer, buffer_apli_trans_rcv.data.buffer); } void retornoTransporte() { if (buffer_apli_trans_env.retorno != 0) if (buffer_apli_trans_env.tipo == CONECTAR) { printf("[APLIC - RET]Alocado o buffer -> end_buffer: '%p' \\n", buffer_apli_trans_env.retorno); printf("Esperando syn para estabelecer conexão!\\n"); } else if (buffer_apli_trans_env.tipo == DESCONECTAR) { printf("[APLIC - RET]Conexão encerrada com sucesso! end_buffer: '%p' \\n", buffer_apli_trans_env.retorno); } }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void *producer(void *ptr) { int i; for (i = 1; i <= 1000000000; i++) { pthread_mutex_lock(&the_mutex); while(buffer != 0) { pthread_cond_wait(&condp, &the_mutex); } buffer = i; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { int i; for (i = 0; i < 1000000000; ++i) { pthread_mutex_lock(&the_mutex); while(buffer == 0) { pthread_cond_wait(&condc, &the_mutex); } buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t pro, con; pthread_mutex_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(pro, 0); pthread_join(con, 0); pthread_cond_destory(&condc); pthread_cond_destory(&condp); pthread_mutex_destory(&the_mutex); return 0; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo{ int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo* foo_alloc(int id) { struct foo *fp; int idx; if((fp = malloc(sizeof(struct foo))) !=0){ fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock,0) !=0) { free(fp); return 0; } idx = (((unsigned long)id) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo* foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id) % 29)];fp!=0;fp=fp->f_next) { if(fp->f_id == id) { fp->f_count--; break; } } pthread_mutex_unlock(&hashlock); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if(--fp->f_count == 0) { idx = (((unsigned long)fp->f_id) % 29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; }else{ while(tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); }else{ pthread_mutex_unlock(&hashlock); } } int main() { exit(0); }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_t tid; int maxNum; int iter; int sum; void *func(void *arg) { (char *)arg; while (1) { pthread_mutex_lock(&lock); iter++; sum += iter; if(maxNum < iter) { printf("sum of 1 - %d is %d\\n", maxNum, sum); pthread_mutex_unlock(&lock); break; } pthread_mutex_unlock(&lock); } if (!strcmp(arg,"2")) { printf("in 2 position\\n"); sleep(100); } } int main(int argc, char *argv[]) { int result; if (3 != argc) { printf("usage: ./a.out <stop-posion> <iteration num>\\n"); return -1;} maxNum = atoi(argv[2]); iter = 0; if (!strcmp(argv[1],"1")) { printf("in 1 position\\n"); sleep(100); } result = pthread_create(&tid, 0, func, &argv[1]); if (0 != result) { printf("create thread error!\\n"); } printf("create thread success!\\n"); while (1) { pthread_mutex_lock(&lock); iter++; sum += iter; if(maxNum < iter) { printf("sum of 1 - %d is %d\\n", maxNum, sum); pthread_mutex_unlock(&lock); break; } pthread_mutex_unlock(&lock); } if (!strcmp(argv[1],"2")) { printf("in 2 position\\n"); sleep(100); } }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; static void sig_int(int signo){ printf("catch sigint:%ld\\n",(unsigned long)pthread_self()); } void *thr_fn(void *arg){ int err, signo; signal(SIGINT, sig_int); for(;;){ printf("new thread sigwait\\n"); err = sigwait(&mask, &signo); if(err != 0){ err_exit(err, "sigwait failed"); } switch(signo){ case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: printf("\\nquit\\n"); pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(void){ 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"); err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0){ err_exit(err, "can't create thread"); } printf("success to create a new thread\\n"); pthread_mutex_lock(&lock); while(quitflag == 0){ printf("you will see block in main thread!\\n"); pthread_cond_wait(&waitloc, &lock); } pthread_mutex_unlock(&lock); quitflag = 0; printf("main thread quitflag = %d\\n", quitflag); if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0){ err_sys("SIG_SETMASK error"); } sleep(1); exit(0); }
0
#include <pthread.h> struct cell { int player_id; pthread_mutex_t cell_lock; }; struct field { pthread_rwlock_t field_lock; struct cell* cells; }; int dim = 0; int min_players; int player_count = 0; int delay = 0; int join_countdown = 10000; struct field* field; void request_global_lock(); void release_global_lock(); pthread_cond_t join_ready = PTHREAD_COND_INITIALIZER; pthread_mutex_t join_lock = PTHREAD_MUTEX_INITIALIZER; int initialize_field_manager(int size) { join_countdown = size/2; field = malloc(sizeof(struct field)); field->cells = 0; if (pthread_rwlock_init(&field->field_lock, 0) != 0) { perror("could not initialize field lock"); return -1; } dim = 0; delay = 0; set_size(size); player_count = 0; return 1; } void release_field_manager() { request_global_lock(); int i; for (i = 0; i < (dim*dim); i++) { struct cell tmpcell = field->cells[i]; pthread_mutex_destroy(&tmpcell.cell_lock); } free(field->cells); free(field); release_global_lock(); pthread_rwlock_destroy(&field->field_lock); dim = 0; delay = 0; join_countdown = 10000; } void request_global_lock() { pthread_rwlock_wrlock(&field->field_lock); } void release_global_lock() { pthread_rwlock_unlock(&field->field_lock); } void request_global_read() { pthread_rwlock_rdlock(&field->field_lock); } void release_global_read() { pthread_rwlock_unlock(&field->field_lock); } int request_cell_lock(int x, int y) { if (get_cell(x, y) == 0) { return -1; } return pthread_mutex_trylock(&get_cell(x, y)->cell_lock); } void release_cell_lock(int x, int y) { pthread_mutex_unlock(&get_cell(x, y)->cell_lock); } struct cell * create_new_cells(int n) { struct cell *new_cells = malloc(sizeof(struct cell) * n); if (new_cells == 0) perror("out of memory"); int i; for (i = 0; i < n ; i++) { new_cells[i].player_id = -1; if (pthread_mutex_init(&new_cells[i].cell_lock, 0) != 0) { return (0); } } return new_cells; } void _set_size(int n) { int new_count = n * n; int current_count = dim * dim; int diff = new_count - current_count; if (diff > 0) { struct cell* new_cells = create_new_cells(diff); if(dim > 0){ field->cells = realloc(field->cells, sizeof(struct cell) * new_count); memcpy(&field->cells[current_count], new_cells, sizeof(struct cell) * diff); free(new_cells); }else { field->cells = new_cells; } new_cells = 0; } else if (diff < 0) { int i; for (i = 0; i < diff; i++) { realloc(field->cells, sizeof(struct cell) * new_count); } } dim = n; min_players = dim / 2; } void set_size(int n) { request_global_lock(); _set_size(n); release_global_lock(); } void increment_size() { request_global_lock(); _set_size((dim + 1)); release_global_lock(); } void decrement_size() { request_global_lock(); _set_size((dim - 1)); release_global_lock(); } int get_size() { return dim * dim; } int get_dim() { return dim; } int coords_to_index(int x, int y) { if (x > dim || y > dim || x < 0 || y < 0){ return - 2; } int max = (((x) > (y)) ? (x) : (y)) + 1; int min = (((x) < (y)) ? (x) : (y)) + 1; int diff = max - min; int cell_index = (max * max) - (2*diff); if (y > x) cell_index++; return cell_index - 1; } struct cell* get_cell(int x, int y) { if (coords_to_index(x, y) < 0) { return 0; } return &field->cells[coords_to_index(x, y)]; } int take_cell(int x, int y, int player_id) { int respsonse; request_global_read(); int result = request_cell_lock(x, y); if (result == 0) { get_cell(x, y)->player_id = player_id; sleep(delay); release_cell_lock(x, y); respsonse = 1; }else{ respsonse= result; } release_global_read(); return respsonse; } int get_cell_player(int x, int y) { return get_cell(x, y)->player_id; } int join_game() { pthread_mutex_lock(&join_lock); if (--join_countdown > 0) pthread_cond_wait(&join_ready, &join_lock); pthread_mutex_unlock(&join_lock); pthread_cond_signal(&join_ready); sleep(1); return 0; } int leave_game() { player_count--; if (player_count < 1) { } return 0; } void set_delay(int n) { delay = n; } int is_there_a_winner() { request_global_lock(); if(dim < 2) { release_global_lock(); return -1; } struct cell cell = field->cells[0]; int winning_player = cell.player_id; int i; for (i = 1; i < (dim * dim); i++) { struct cell next_cell = field->cells[i]; if (next_cell.player_id == winning_player) { }else{ release_global_lock(); return -1; } } release_global_lock(); return winning_player; }
1
#include <pthread.h> int number; pthread_mutex_t mutex; void* funcA_num(void* arg) { for(int i=0; i<10000; ++i) { pthread_mutex_lock(&mutex); int cur = number; cur++; number = cur; printf("Thread A, id = %lu, number = %d\\n", pthread_self(), number); pthread_mutex_unlock(&mutex); usleep(10); } return 0; } void* funcB_num(void* arg) { for(int i=0; i<10000; ++i) { pthread_mutex_lock(&mutex); int cur = number; cur++; number = cur; printf("Thread B, id = %lu, number = %d\\n", pthread_self(), number); pthread_mutex_unlock(&mutex); usleep(10); } return 0; } int main(int argc, const char* argv[]) { pthread_t p1, p2; pthread_mutex_init(&mutex,0); pthread_create(&p1, 0, funcA_num, 0); pthread_create(&p2, 0, funcB_num, 0); pthread_join(p1, 0); pthread_join(p2, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> void pipeline_link_pipe_init(struct pipeline_link_pipe* link, unsigned int buffer_size) { pipeline_link_init((struct pipeline_link*)link, pipeline_link_pipe_push, pipeline_link_pipe_pop, pipeline_link_pipe_is_full, pipeline_link_pipe_is_empty, pipeline_link_pipe_is_ready_to_pop, pipeline_link_pipe_saturation, pipeline_link_pipe_free); pthread_mutex_init(&(link->writers_mutex), 0); pthread_mutex_init(&(link->readers_mutex), 0); pthread_mutex_init(&(link->buffer_not_empty_mutex), 0); pthread_mutex_init(&(link->buffer_not_full_mutex), 0); pthread_mutex_init(&(link->cursor_mutex), 0); pthread_mutex_lock(&(link->buffer_not_empty_mutex)); link->state = PIPELINE_LINK_PIPE_EMPTY; link->input_cursor = 0; link->output_cursor = 0; link->buffer_size = buffer_size; link->buffer = (void**) malloc(sizeof(void*)*link->buffer_size); } struct pipeline_link_pipe* pipeline_link_pipe_create(unsigned int buffer_size) { struct pipeline_link_pipe* ret = (struct pipeline_link_pipe*) malloc(sizeof(struct pipeline_link_pipe)); pipeline_link_pipe_init(ret, buffer_size); return ret; } int pipeline_link_pipe_push(struct pipeline_link* link, void* obj_in, struct timespec* timeout) { struct pipeline_link_pipe* pipe = (struct pipeline_link_pipe*) link; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->writers_mutex), timeout) != 0) return PIPELINE_SIG_TIMEOUT; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->buffer_not_full_mutex), timeout) != 0) { pthread_mutex_unlock(&(pipe->writers_mutex)); return PIPELINE_SIG_TIMEOUT; } pipe->buffer[pipe->input_cursor] = obj_in; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->cursor_mutex), timeout) != 0) { pthread_mutex_unlock(&(pipe->buffer_not_full_mutex)); pthread_mutex_unlock(&(pipe->writers_mutex)); return PIPELINE_SIG_TIMEOUT; } if(pipe->input_cursor == pipe->output_cursor) { pipe->state &= !PIPELINE_LINK_PIPE_EMPTY; pthread_mutex_unlock(&(pipe->buffer_not_empty_mutex)); } pipe->input_cursor++; if(pipe->input_cursor >= pipe->buffer_size) pipe->input_cursor = 0; if(pipe->input_cursor != pipe->output_cursor) pthread_mutex_unlock(&(pipe->buffer_not_full_mutex)); else pipe->state |= PIPELINE_LINK_PIPE_FULL; pthread_mutex_unlock(&(pipe->cursor_mutex)); pthread_mutex_unlock(&(pipe->writers_mutex)); return PIPELINE_SIG_OK; } int pipeline_link_pipe_pop(struct pipeline_link* link, void** obj_out, struct timespec* timeout) { struct pipeline_link_pipe* pipe = (struct pipeline_link_pipe*) link; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->readers_mutex), timeout) != 0) return PIPELINE_SIG_TIMEOUT; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->buffer_not_empty_mutex), timeout) != 0) { pthread_mutex_unlock(&(pipe->readers_mutex)); return PIPELINE_SIG_TIMEOUT; } *obj_out = pipe->buffer[pipe->output_cursor]; if(timeout == 0) pthread_mutex_lock(&(pipe->readers_mutex)); else if(pthread_mutex_timedlock(&(pipe->cursor_mutex), timeout) != 0) { pthread_mutex_unlock(&(pipe->buffer_not_empty_mutex)); pthread_mutex_unlock(&(pipe->readers_mutex)); return PIPELINE_SIG_TIMEOUT; } if(pipe->input_cursor == pipe->output_cursor) { pipe->state &= !PIPELINE_LINK_PIPE_FULL; pthread_mutex_unlock(&(pipe->buffer_not_full_mutex)); } pipe->output_cursor++; if(pipe->output_cursor >= pipe->buffer_size) pipe->output_cursor = 0; if(pipe->input_cursor != pipe->output_cursor) pthread_mutex_unlock(&(pipe->buffer_not_empty_mutex)); else pipe->state |= PIPELINE_LINK_PIPE_EMPTY; pthread_mutex_unlock(&(pipe->cursor_mutex)); pthread_mutex_unlock(&(pipe->readers_mutex)); return PIPELINE_SIG_OK; } int pipeline_link_pipe_is_full(struct pipeline_link* link) { return (((struct pipeline_link_pipe*)link)->state & PIPELINE_LINK_PIPE_FULL) != 0; } int pipeline_link_pipe_is_empty(struct pipeline_link* link) { return (((struct pipeline_link_pipe*)link)->state & PIPELINE_LINK_PIPE_EMPTY) != 0; } int pipeline_link_pipe_is_ready_to_pop(struct pipeline_link* link) { return (((struct pipeline_link_pipe*)link)->state & PIPELINE_LINK_PIPE_EMPTY) == 0; } int pipeline_link_pipe_saturation(struct pipeline_link* link) { struct pipeline_link_pipe* pipe = (struct pipeline_link_pipe*) link; if(pipe->input_cursor > pipe->output_cursor) return pipe->input_cursor - pipe->output_cursor; else return (pipe->buffer_size + pipe->input_cursor) - pipe->output_cursor; } int pipeline_link_pipe_free(struct pipeline_link* link) { struct pipeline_link_pipe* pipe = (struct pipeline_link_pipe*) link; pthread_mutex_destroy(&(pipe->readers_mutex)); pthread_mutex_destroy(&(pipe->writers_mutex)); pthread_mutex_destroy(&(pipe->buffer_not_empty_mutex)); pthread_mutex_destroy(&(pipe->buffer_not_full_mutex)); pthread_mutex_destroy(&(pipe->cursor_mutex)); free(pipe->buffer); free(pipe); return PIPELINE_SIG_OK; }
1
#include <pthread.h> pthread_mutex_t barrier; pthread_cond_t go; int numWorkers; int numArrived = 0; void Barrier() { pthread_mutex_lock(&barrier); numArrived++; if (numArrived == numWorkers) { numArrived = 0; pthread_cond_broadcast(&go); } else pthread_cond_wait(&go, &barrier); pthread_mutex_unlock(&barrier); } double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size, stripSize; int sums[10]; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_cond_init(&go, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = 1; } } start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); pthread_exit(0); } void *Worker(void *arg) { long myid = (long) arg; int total, i, j, first, last; first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); total = 0; for (i = first; i <= last; i++) for (j = 0; j < size; j++) total += matrix[i][j]; sums[myid] = total; Barrier(); if (myid == 0) { total = 0; for (i = 0; i < numWorkers; i++) total += sums[i]; end_time = read_timer(); printf("The total is %d\\n", total); printf("The execution time is %g sec\\n", end_time - start_time); } }
0
#include <pthread.h> static char* output_string = 0; static pthread_mutex_t output_lock; static int initialized = 0; static pthread_t thread; static void* query_brightness_thread() { if( output_string == 0 ) { output_string = calloc( 32, sizeof(char) ); } while( initialized ) { FILE *fp; char brightness[8]; fp = fopen("/sys/class/backlight/acpi_video0/brightness", "r"); fscanf( fp, "%s\\n", brightness ); fclose(fp); pthread_mutex_lock( &output_lock ); strncpy( output_string, "Brightness: ", 32 -1 ); strncat( output_string, brightness, 32 -1 ); pthread_mutex_unlock( &output_lock ); usleep( 100000 ); } free( output_string ); output_string = 0; return 0; } int brightness_init() { if( initialized ) return 0; pthread_mutex_init( &output_lock, 0 ); pthread_create( &thread, 0, &query_brightness_thread, 0 ); initialized = 1; return 1; } int brightness_destroy() { if( !initialized ) return 0; initialized = 0; pthread_join( thread, 0 ); pthread_mutex_destroy( &output_lock ); return 1; } char* get_brightness_information() { if( !initialized ) return 0; char* brightness_string = calloc( 32, sizeof(char) ); pthread_mutex_lock( &output_lock ); if( output_string ) strncpy( brightness_string, output_string, 32 -1 ); pthread_mutex_unlock( &output_lock ); return brightness_string; }
1
#include <pthread.h> pthread_mutex_t mutex; void *myfunc(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_t t; pthread_mutex_init(&mutex, 0); pthread_create(&t, 0, myfunc, 0); int ret; if ((ret = fork()) > 0) { wait(0); printf("\\ntest done by parent: pid %d, ret pid %d\\n\\n\\n", getpid(), ret); return 0; } assert(ret == 0); printf("\\ntest done start pid %d\\n\\n\\n", getpid()); pthread_mutex_init(&mutex, 0); printf("\\ntest done start2 pid %d\\n\\n\\n", getpid()); pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); printf("test done\\n\\n\\n"); return 0; }
0
#include <pthread.h> void *raw_socket(void *pParam){ struct frame_queue *temp; int sockfd,on = 1; struct sniff_ip *iph; int len,iph_len; struct sockaddr_in dst_sin; ssize_t size; int i; unsigned char *data; unsigned short recv_sum,calc_sum; char message[150]; sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW); if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) { sprintf(message,"error:socket\\n"); enq_log(message); fprintf(stderr,"error:socket\\n"); usleep(ERRTO); exit(1); } if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) { sprintf(message,"error:setsockopt\\n"); enq_log(message); fprintf(stderr,"error:setsockopt\\n"); usleep(ERRTO); exit(1); } sprintf(message,"thread: start raw_socket\\n"); enq_log(message); printf("thread: start raw_socket\\n"); while(1){ pthread_mutex_lock(&mutex2); while (recvque_total==0){ pthread_cond_wait(&cond2,&mutex2); } temp = recvque_head; iph=(struct sniff_ip*)(temp->data); recv_sum = iph->ip_sum; iph_len = IP_HL(iph)*4; iph->ip_sum = (unsigned short)0x00; calc_sum = checksum((unsigned short*)iph,iph_len); if(calc_sum == recv_sum){ dst_sin.sin_addr.s_addr = (iph->ip_dst).s_addr; dst_sin.sin_family = AF_INET; dst_sin.sin_port = htons(0); len = temp->length; data = (unsigned char*)malloc(len); if(data == 0){ sprintf(message,"error: cannot malloc\\n"); enq_log(message); fprintf(stderr,"error: cannot malloc\\n"); usleep(ERRTO); exit(1); } for (i = 0;i < len;i++){ data[i] = temp->data[i]; } if ((size = sendto(sockfd, (void *)data, len, 0,&dst_sin, sizeof(dst_sin))) == -1){ sprintf(message,"error: sendto"); enq_log(message); fprintf(stderr,"error: sendto"); usleep(ERRTO); exit(1); } enq_log_ip((unsigned char*)data,"send(eth): "); free(data); data = 0; } else{ } if(temp->next == 0){ free(recvque_head); recvque_head = 0; recvque_total = 0; } else{ recvque_head = recvque_head->next; free(temp); recvque_total--; } pthread_mutex_unlock(&mutex2); } }
1
#include <pthread.h> struct foo * fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo * f_next; }; struct foo * foo_alloc (int id ) { struct foo * fp; int idx; if ((fp = (struct foo * ) malloc (sizeof (struct foo ))) != 0) { fp -> f_count = 1; fp -> f_id = id; if (pthread_mutex_init (&fp -> f_lock, 0) != 0) { free (fp); return 0; } idx = HASH (id); pthread_mutex_lock (&hashlock); fh[idx] = fp; pthread_mutex_lock (&fp -> flock ); pthread_mutex_unlock (&hashlock ); pthread_mutex_unlock (&fp -> f_lock ); } return fp; } void foo_hold (struct foo * fp ) { pthread_mutex_lock (&fp -> f_lock ); fp -> f_count++; pthread_mutex_unlock (&fp -> f_lock ); } struct foo * foo_find (int id ) { struct foo * fp; pthread_mutex_lock (&hashlock ); for (fp = fh[HASH (id)]; fp != 0; fp = fp -> f_next ) { if (fp -> f_id == id) { foo_hold (fp); break; } } pthread_mutex_unlock (&hashlock ); return fp; } void foo_rele (struct foo * fp) { struct foo * tfp; int idx; pthread_mutex_lock (&fp -> f_lock); if (fp -> f_count == 1 ) { pthread_mutex_unlock (&fp -> f_lock ); pthread_mutex_lock (&hashlock ); pthread_mutex_lock (&fp -> f_lock ); if (fp -> f_count != 1) { fp -> f_count--; pthread_mutex_unlock (&fp -> f_lock ); pthread_mutex_unlock (&hashlock ); return ; } idx = HASH (fp -> f_id ); tfp = fh[idx]; if (tfp == fp) fh[idx] == fp -> f_next; else { while (tfp -> f_next != fp) tfp = tfp -> f_next; tfp -> f_next = fp -> f_next; } pthread_mutex_unlock (&hashlock ); ptherad_mutex_unlock (&fp -> f_lock ); pthread_mutex_destroy (&fp -> f_lock ); free (fp); } else { fp -> f_count--; pthread_mutex_unlock (&fp -> f_lock ); } }
0
#include <pthread.h> pthread_mutex_t globalMutex[2]; pthread_cond_t globalCondVar[2]; static void *threadFunc1(void *args) { assert(args == 0); pthread_mutex_lock(&globalMutex[0]); pthread_cond_wait(&globalCondVar[0], &globalMutex[0]); printf("X modified by threadFunc 1\\n"); pthread_mutex_unlock(&globalMutex[0]); return 0; } static void *threadFunc2(void *args) { assert(args == 0); pthread_mutex_lock(&globalMutex[1]); pthread_cond_wait(&globalCondVar[1], &globalMutex[1]); printf("X Modified by threadFunc 2\\n"); pthread_mutex_unlock(&globalMutex[1]); return 0; } int main(void) { pthread_t thread[2]; pthread_mutex_init(&globalMutex[0], 0); pthread_mutex_init(&globalMutex[1], 0); pthread_cond_init(&globalCondVar[0], 0); pthread_cond_init(&globalCondVar[1], 0); pthread_create(&thread[0], 0, threadFunc1, 0); pthread_create(&thread[1], 0, threadFunc2, 0); pthread_cond_signal(&globalCondVar[0]); pthread_cond_signal(&globalCondVar[1]); pthread_join(thread[1], 0); pthread_join(thread[0], 0); pthread_cond_destroy(&globalCondVar[0]); pthread_cond_destroy(&globalCondVar[1]); pthread_mutex_destroy(&globalMutex[0]); pthread_mutex_destroy(&globalMutex[1]); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; int Var = 0; void *thread_function2(void *arg) { while (1) { sleep(1); pthread_mutex_lock(&lock); Var++; pthread_mutex_unlock(&lock); printf("I am in Thread2 Var = %d\\n", Var); } pthread_exit("Exit from Thread\\n"); } void *thread_function1(void *arg) { while (1) { sleep(1); pthread_mutex_lock(&lock); Var++; pthread_mutex_unlock(&lock); printf("I am in Thread1 Var = %d\\n", Var); } pthread_exit("Exit from Thread\\n"); } int main() { int i = 0; int res; pthread_t a_thread1; pthread_t a_thread2; void *thread_result; pthread_mutex_init(&lock,0); res = pthread_create(&a_thread1, 0, thread_function1, (void *)0); if (res != 0) { perror("Thread creation failed"); exit(1); } res = pthread_create(&a_thread2, 0, thread_function2, (void *)0); if (res != 0) { perror("Thread creation failed"); exit(1); } while(1); exit(0); }
0
#include <pthread.h> int q[5]; int source[7]; int qsiz; pthread_mutex_t mq; void *queue_insert (void * arg) { int done = 0; int i = 0; int x = 1; qsiz = 5; while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 5) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } pthread_exit(0); } int main () { pthread_t t; for (int i = 0; i < 7; i++) { source[i] = nondet(0,20); if (source[i] < 0) { poet_error(); } } pthread_create (&t, 0, queue_insert, 0); pthread_join (t, 0); return 0; }
1
#include <pthread.h> struct pthread_args { long iterations; pthread_mutex_t mutex; }; void *calculate_pi(void *ptr) { struct pthread_args *attr = ptr; double lsum = 0.0; for(;;) { pthread_mutex_lock(&(attr->mutex)); long i = attr->iterations; attr->iterations = attr->iterations + 10; pthread_mutex_unlock(&(attr->mutex)); if((i + 10) > 1000000) { break; } double lower = (0.5 + i)*1.0/1000000; double upper = (i + 10)*1.0/1000000; while(lower<upper) { lsum = lsum + sqrt(1-lower*lower) * 1.0/1000000; lower += 1.0/1000000; } } double *temp = malloc(sizeof(double)); *temp = lsum; return temp; } int main(int argc, char **argv) { void *lsum; double sum = 0.0; pthread_t *thread; struct pthread_args args = {0, PTHREAD_MUTEX_INITIALIZER}; thread = malloc(4 * sizeof(*thread)); for(int i=0;i<4;i++) { pthread_create(thread+i,0,&calculate_pi,&args); } for(int i=0;i<4;i++) { pthread_join(thread[i],&lsum); sum+= *((double*)lsum); } sum*=4; printf("Calculated PI is %.10lf\\n",sum); printf("Error in PI is %.10lf\\n",M_PI-sum); return 0; }
0
#include <pthread.h> struct { int maxproc; int *pids; int terminate; procfunc_t func; void *param; pthread_mutex_t mutex; pthread_cond_t cond; } PCtrlParam; static void *_monitor(void *); static void _sigusr1(int sig); static void _sigusr1_child_default(int sig); int pct_parallel(int maxproc, procfunc_t func, void *param) { int i, rc; int pid; pthread_t monpth; signal(SIGUSR1, _sigusr1); signal(SIGTERM, _sigusr1); signal(SIGCHLD, SIG_DFL); PCtrlParam.maxproc = maxproc; PCtrlParam.func = func; PCtrlParam.param = param; PCtrlParam.terminate = 0; PCtrlParam.pids = (int *)malloc(sizeof(int) * maxproc); if (PCtrlParam.pids == 0) { return (-50); } for (i=0; i< maxproc; i++) { PCtrlParam.pids[i] = 0; } if (pthread_mutex_init(&(PCtrlParam.mutex), 0) < 0) { return (-57); } if (pthread_cond_init(&(PCtrlParam.cond), 0) < 0) { return (-61); } if (pthread_create(&monpth, 0, _monitor, 0) != 0) { return (-65); } while (1) { if ((pid = wait(0)) > 0) { pthread_mutex_lock(&(PCtrlParam.mutex)); for (i=0; i<PCtrlParam.maxproc; i++) { if (PCtrlParam.pids[i] == pid) { PCtrlParam.pids[i] = 0; } } pthread_mutex_unlock(&(PCtrlParam.mutex)); pthread_cond_signal(&(PCtrlParam.cond)); } if (PCtrlParam.terminate) { break; } } return (0); } static void *_monitor(void *p) { int i, rc, pid; time_t t; struct timespec ts; for (i=0; i<PCtrlParam.maxproc; i++) { PCtrlParam.pids[i] = fork(); if (PCtrlParam.pids[i] == 0) { signal(SIGTERM, _sigusr1_child_default); signal(SIGUSR1, _sigusr1_child_default); PCtrlParam.func(i, PCtrlParam.param); exit (0); } } while (1) { rc = 0; pthread_mutex_lock(&(PCtrlParam.mutex)); while (rc == 0) { if (PCtrlParam.terminate == 1) { break; } for (i=0; i<PCtrlParam.maxproc; i++) { if (PCtrlParam.pids[i] <= 0) { rc = 1; break; } } if (rc == 0) { t = time(0); ts.tv_sec = t + 10; ts.tv_nsec = 0; pthread_cond_timedwait(&(PCtrlParam.cond), &(PCtrlParam.mutex), &ts); } } pthread_mutex_unlock(&(PCtrlParam.mutex)); if (PCtrlParam.terminate == 1) { break; } for (i=0; i<PCtrlParam.maxproc; i++) { pthread_mutex_lock(&(PCtrlParam.mutex)); pid = PCtrlParam.pids[i]; pthread_mutex_unlock(&(PCtrlParam.mutex)); if (pid <= 0) { pid = fork(); if (pid == 0) { signal(SIGTERM, _sigusr1_child_default); signal(SIGUSR1, _sigusr1_child_default); PCtrlParam.func(i, PCtrlParam.param); exit (0); } else if (pid > 0) { pthread_mutex_lock(&(PCtrlParam.mutex)); PCtrlParam.pids[i] = pid; pthread_mutex_unlock(&(PCtrlParam.mutex)); } else { pthread_mutex_lock(&(PCtrlParam.mutex)); PCtrlParam.pids[i] = 0; pthread_mutex_unlock(&(PCtrlParam.mutex)); } } } } return (0); } static void _sigusr1(int sig) { int i; PCtrlParam.terminate = 1; for (i=0; i<PCtrlParam.maxproc; i++) { if (PCtrlParam.pids[i] > 0) { kill(PCtrlParam.pids[i], SIGUSR1); } } signal(sig, _sigusr1); } static void _sigusr1_child_default(int sig) { exit (0); }
1
#include <pthread.h> struct xml_cntn_rcvr *xml_cntn_rcvr_create() { struct xml_cntn_rcvr *new = malloc(sizeof(*new)); new->seq = 0; new->subcllst = 0; assert(!pthread_cond_init(&new->cond, 0)); assert(!pthread_mutex_init(&new->mutex, 0)); return new; } void xml_cntn_rcvr_delete(struct xml_cntn_rcvr *rcvr) { pthread_cond_destroy(&rcvr->cond); pthread_mutex_destroy(&rcvr->mutex); free(rcvr); } int xml_cntn_rcvr_subcl_activate(struct xml_cntn_rcvr *rcvr, struct xml_cntn_subcl* subcl) { if (pthread_mutex_lock(&rcvr->mutex) != 0){ fprintf(stderr, "ERROR: No mutex lock in %s\\n", __FUNCTION__); return -1; } xml_cntn_subcl_activate(subcl, ++rcvr->seq); rcvr->subcllst = xml_cntn_subcl_list_add(rcvr->subcllst, subcl); pthread_mutex_unlock(&rcvr->mutex); return 0; } int xml_cntn_rcvr_subcl_cancel(struct xml_cntn_rcvr *rcvr, struct xml_cntn_subcl* subcl) { if (pthread_mutex_lock(&rcvr->mutex) != 0) return -1; rcvr->subcllst = xml_cntn_subcl_list_rem(rcvr->subcllst, subcl); xml_cntn_subcl_cancel(subcl); pthread_mutex_unlock(&rcvr->mutex); return 0; } struct xml_item *xml_cntn_rcvr_subcl_wait(struct xml_cntn_rcvr *rcvr, struct xml_cntn_subcl* subcl, int timeout) { struct xml_item *items = 0; struct timespec ts_timeout; int retval = 0; clock_gettime(CLOCK_REALTIME, &ts_timeout); ts_timeout.tv_sec += timeout/1000; ts_timeout.tv_nsec += (timeout%1000)*1000000; if(ts_timeout.tv_nsec >= 1000000000){ ts_timeout.tv_nsec -= 1000000000; ts_timeout.tv_sec += 1; } if (pthread_mutex_lock(&rcvr->mutex) != 0) return 0; while (subcl->item == 0) { if(timeout > 0) retval = pthread_cond_timedwait(&rcvr->cond, &rcvr->mutex, &ts_timeout); else retval = pthread_cond_wait(&rcvr->cond, &rcvr->mutex); if (retval) { PRINT_ERR("pthread_cond_timed[wait] failed (seqtag %s, timeout %d): return: %s (%d)", subcl->seqtag, timeout, strerror(retval), retval ); PRINT_ERR("pthread_cond_timed[wait]: %p %p", &rcvr->cond, &rcvr->mutex); break; } } items = subcl->item; subcl->item = 0; pthread_mutex_unlock(&rcvr->mutex); return items; } int xml_cntn_rcvr_tag(struct spxml_cntn *cntn, struct xml_item *item) { struct xml_cntn_rcvr *rcvr = (struct xml_cntn_rcvr*)cntn->userdata; const char *seq = xml_item_get_attr(item, "seq"); const char *tag = item->name; int found = 0; if (pthread_mutex_lock(&rcvr->mutex) != 0) return -1; struct xml_cntn_subcl* ptr = rcvr->subcllst; while (ptr) { if(xml_cntn_subcl_match(ptr, seq, tag)){ ptr->item = xml_item_list_add(ptr->item, xml_item_create_copy(0, item, 0)); ptr->rcvcnt++; found = 1; break; } ptr = ptr->next; } pthread_cond_broadcast(&rcvr->cond); pthread_mutex_unlock(&rcvr->mutex); if (!found) { PRINT_ERR("seq not found %s/%s", seq, tag); } return found; }
0
#include <pthread.h> int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void wait_n_secs(int seconds, unsigned char show_output) { int i; for (i = 1; i <= seconds; ++i) { usleep(1000000); if (show_output) printf("Second %d\\n", i); } } void do_work() { static int counter = 0; printf("do_work() counting %d\\n", counter); ++counter; usleep(1000000/3); } void initialize_flag() { pthread_mutex_init(&thread_flag_mutex, 0); thread_flag = 0; } void* thread_function(void* thread_arg) { while (1) { int flag_is_set; pthread_mutex_lock(&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock(&thread_flag_mutex); if (flag_is_set) do_work(); } return 0; } void set_thread_flag(int flag_value) { pthread_mutex_lock(&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock(&thread_flag_mutex); } int main(int argc, char** argv) { pthread_t thread1, thread2; initialize_flag(); printf("Creating new thread\\n"); pthread_create(&thread1, 0, thread_function, 0); printf("New thread created\\n"); printf("Wait 5 seconds\\n"); wait_n_secs(5, 1); printf("Now a new thread will run with output\\n" "Press Enter to block the thread\\n"); set_thread_flag(1); getchar(); set_thread_flag(0); printf("Thread is blocked, so now we will " "cancel it to exit the program\\n"); pthread_cancel(thread1); return 0; }
1
#include <pthread.h> int SIZE = 500; int generations_amount = 500; int num = 0; int freq = 100; pthread_t thread[8]; pthread_t thread_init; int end[8]; char map[2][8000][8000]; unsigned long long mask = 0; int was_printed = 0; int was_initialized = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER, mutex_init = PTHREAD_MUTEX_INITIALIZER; int temp[8]; pthread_barrier_t barrier_life_game_step; pthread_barrier_t barrier_life_game_step_end; pthread_barrier_t barrier_initialization; int add(int x) { if (x == SIZE - 1) return 0; else return x + 1; } int sub(int x) { if (x == 0) return SIZE - 1; else return x - 1; } int alive(int step, int x, int y) { int al = 0; if (map[step][sub(x)][sub(y)] == 1) ++al; if (map[step][sub(x)][y] == 1) ++al; if (map[step][sub(x)][add(y)] == 1) ++al; if (map[step][x][sub(y)] == 1) ++al; if (map[step][x][add(y)] == 1) ++al; if (map[step][add(x)][sub(y)] == 1) ++al; if (map[step][add(x)][y] == 1) ++al; if (map[step][add(x)][add(y)] == 1) ++al; return al; } void recalc(int step, int x, int y) { if (map[step][x][y] == 0) { if (alive(step, x, y) == 3) map[1 ^ step][x][y] = 1; else map[1 ^ step][x][y] = 0; } if (map[step][x][y] == 1) { if (alive(step, x, y) == 3 || alive(step, x, y) == 2) map[1 ^ step][x][y] = 1; else map[1 ^ step][x][y] = 0; } } void print_map(int step, int field_size) { system("clear"); int i, j; for (i = 0; i < field_size; i++){ for (j = 0; j < field_size; j++) printf("%s ", map[(step & 1) ^ 1][i][j] ? "■" : "."); printf("\\n"); } } int check_if_game_over() { int i; for (i = 0; i < 8; i++) { if (end[i] == 1) { return 0; } } return 1; } void try_print_map(int step) { pthread_mutex_lock(&lock); if (!was_printed) { was_initialized = 0; if (step % freq == 0) print_map(step, SIZE < 40 ? SIZE : 40); was_printed = 1; } pthread_mutex_unlock(&lock); } void initizlize_variables() { pthread_mutex_lock(&mutex_init); if (!was_initialized) { was_printed = 0; int i; for (i = 0; i < 8; ++i) { end[i] = 0; } was_initialized = 1; } pthread_mutex_unlock(&mutex_init); } void* life_1(void* arg) { int life_game_step; for (life_game_step = 0; life_game_step < generations_amount;life_game_step++) { initizlize_variables(); pthread_barrier_wait(&barrier_initialization); int i, j; int id = *(int*)arg; for (i = id; i < id + (SIZE / 8); i++) { for (j = 0; j < SIZE; j++) { recalc(life_game_step & 1, i, j); if (map[0][i][j] != map[1][i][j]) end[(id * 8) / SIZE] = 1; } } pthread_barrier_wait(&barrier_life_game_step); try_print_map(life_game_step); if (0 & check_if_game_over()) { printf("GAME OVER DETECTED\\n"); return 0; } pthread_barrier_wait(&barrier_life_game_step_end); } return 0; } int main(int argc, char ** argv) { struct timeval tv1, tv2; gettimeofday(&tv1, 0); if (argc < 2) { printf("bad params: using: ./life_thread field_size steps_amount print_freq\\n"); return 0; } if (argc > 1) { SIZE = atoi(argv[1]); } if (argc > 2) { generations_amount = atoi(argv[2]); } if (argc > 3) { freq = atoi(argv[3]); } int status; int i, j; srand(time(0)); for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) map[0][i][j] = rand() % 2; pthread_barrier_init(&barrier_life_game_step, 0, 8); pthread_barrier_init(&barrier_life_game_step_end, 0, 8); pthread_barrier_init(&barrier_initialization, 0, 8); int k; for (k = 0; k < 8; k++){ temp[k] = k * (SIZE / 8); status = pthread_create(&thread[k], 0, life_1, &temp[k]); if (status != 0) perror("error pthread creating\\n"); } for (k = 0; k < 8; ++k) { pthread_join(thread[k], 0); } gettimeofday(&tv2, 0); printf ("Total time = %f seconds\\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); return 0; }
0
#include <pthread.h> { pthread_mutex_t mutex; pthread_cond_t cond; } Lock_pl_t; void LOCK_PL_init(void **handle) { Lock_pl_t *lock = (Lock_pl_t *)malloc(sizeof(Lock_pl_t)); pthread_mutex_init(&lock->mutex, 0); pthread_cond_init(&lock->cond, 0); *handle = lock; return; } void LOCK_PL_lock(void *inHandle) { Lock_pl_t *lock = (Lock_pl_t *)inHandle; pthread_mutex_lock(&lock->mutex); } void LOCK_PL_unlock(void *inHandle) { Lock_pl_t *lock = (Lock_pl_t *)inHandle; pthread_mutex_unlock(&lock->mutex); } void LOCK_PL_signal(void *inHandle) { Lock_pl_t *lock = (Lock_pl_t *)inHandle; pthread_cond_signal(&lock->cond); } void LOCK_PL_wait(void *inHandle) { Lock_pl_t *lock = (Lock_pl_t *)inHandle; pthread_cond_wait(&lock->cond, &lock->mutex); } void LOCK_PL_term(void *inHandle) { Lock_pl_t *lock = (Lock_pl_t *)inHandle; pthread_mutex_destroy(&lock->mutex); pthread_cond_destroy(&lock->cond); }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static const int N = 5; char warunek = 0; static void* watek(void* numer){ printf("\\t uruchomiono watek numer: %d\\n",(int)numer); while(1){ pthread_mutex_lock(&mutex); do{ if(warunek){ break; } else{ pthread_cond_wait(&cond, &mutex); } }while(1); pthread_mutex_unlock(&mutex); } return 0; } void main_zmienne(){ pthread_t id[N]; int i; puts("Poczatek programu"); for(i = 0; i<N; i++){ errno =pthread_create(&id[i], 0, watek, (void*)(i+1)); test_errno("pthread_create"); } sleep(1); puts("pthread_cond_signal - sygnalizacja"); pthread_cond_signal(&cond); sleep(1); puts("pthread_cond_broadcast - rozgloszenie"); pthread_cond_broadcast(&cond); sleep(10); puts("Koniec programu"); }
0
#include <pthread.h> int is_prime(uint64_t p) { uint64_t premier = 0; uint64_t i=2; while (i<p && premier==0) { if (p%i==0) { premier=1; } i++; } return premier; } void print_prime_factors(uint64_t n) { printf("%lu:", n); uint64_t i=2; while (i<=n) { if (n%i==0) { printf(" %lu", i); n=n/i; } else { i++; } } printf("\\r\\n"); } void read_file(const char * fileName) { uint64_t number = 1; FILE *file=fopen(fileName,"r"); if (file != 0) { while (fscanf(file,"%lu",&number) != EOF) { print_prime_factors(number); } } else { printf("Impossible d'ouvrir le fichier."); } fclose(file); } void *lancerLeTravail(void* tmp) { uint64_t nombre = *( ( uint64_t* ) tmp ); print_prime_factors(nombre); pthread_exit(0); } void lancerLeTravailQuestion6() { pthread_t thread1; FILE *file=fopen("in.txt","r"); uint64_t nombre1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; for(;;) { pthread_mutex_lock(&mutex); if(fscanf(file,"%lu",&nombre1) == EOF) { break; } pthread_create ( &thread1 , 0, &lancerLeTravail, &nombre1); pthread_mutex_unlock (&mutex); } fclose(file); pthread_mutex_destroy( &mutex ); exit(0); } int main () { return 0; }
1
#include <pthread.h> void *sum(void *p); unsigned long int psum; char padding[64 - sizeof(unsigned long int)]; } Psum; Psum psum[8]; unsigned long int sumtotal = 0; unsigned long int n; int numthreads; pthread_mutex_t mutex; int main(int argc, char **argv) { pthread_t tid[8]; int i, myid[8]; struct timeval start, end; gettimeofday(&start, 0); scanf("%lu %d", &n, &numthreads); for (i = 0; i < numthreads; i++) { myid[i] = i; psum[i].psum = 0.0; pthread_create(&tid[i], 0, sum, &myid[i]); } for (i = 0; i < numthreads; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); long spent = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec); printf("%lu\\n%ld\\n", sumtotal, spent); return 0; } void *sum(void *p) { int myid = *((int *) p); unsigned long int start = (myid * (unsigned long int) n) / numthreads; unsigned long int end = ((myid + 1) * (unsigned long int) n) / numthreads; unsigned long int i; for (i = start; i < end; i++) { psum[myid].psum += 2; } pthread_mutex_lock(&mutex); sumtotal += psum[myid].psum; pthread_mutex_unlock(&mutex); return 0 ; }
0
#include <pthread.h> int DEBUG = 0; int NUM_THREADS = 5; int left(int phil_id) { return phil_id; } int right(int phil_id) { if (phil_id == NUM_THREADS - 1) { return 0; } else return phil_id + 1; } static pthread_mutex_t mutexes[5]; void chopsticks_init() { pthread_mutex_init(&mutexes[0], 0); pthread_mutex_init(&mutexes[1], 0); pthread_mutex_init(&mutexes[2], 0); pthread_mutex_init(&mutexes[3], 0); pthread_mutex_init(&mutexes[4], 0); } void chopsticks_destroy(){ pthread_mutex_destroy(&mutexes[0]); pthread_mutex_destroy(&mutexes[1]); pthread_mutex_destroy(&mutexes[2]); pthread_mutex_destroy(&mutexes[3]); pthread_mutex_destroy(&mutexes[4]); } void pickup_chopsticks(int phil_id){ int x = 0; while (x == 0) { pthread_mutex_lock(&mutexes[right(phil_id)] ); if ( pthread_mutex_trylock(&mutexes[left(phil_id)] ) == 0) { if (DEBUG == 1) { int c = phil_id; int a = left(phil_id); int b = right(phil_id); printf("Picking up! %d,%d %d\\n", a, b, c); } pickup_right_chopstick(phil_id); pickup_left_chopstick(phil_id); return; } else { pthread_mutex_unlock(&mutexes[right(phil_id)]); pthread_mutex_lock(&mutexes[left(phil_id)] ); if ( pthread_mutex_trylock(&mutexes[right(phil_id)] ) == 0) { pickup_left_chopstick(phil_id); pickup_right_chopstick(phil_id); return;} else { pthread_mutex_unlock(&mutexes[left(phil_id)]); } } } } void putdown_chopsticks(int phil_id){ putdown_right_chopstick(phil_id); putdown_left_chopstick(phil_id); if (DEBUG == 1) { int a = left(phil_id); int b = right(phil_id); int c = phil_id; printf("Putting down! %d,%d %d\\n", a, b, c); } pthread_mutex_unlock(&mutexes[right(phil_id)]); pthread_mutex_unlock(&mutexes[left(phil_id)]); }
1
#include <pthread.h> static int64_t _hdr_phaser_get_epoch(int64_t* field) { return __atomic_load_n(field, 5); } static void _hdr_phaser_set_epoch(int64_t* field, int64_t val) { __atomic_store_n(field, val, 5); } static int64_t _hdr_phaser_reset_epoch(int64_t* field, int64_t initial_value) { return __atomic_exchange_n(field, initial_value, 5); } int hdr_writer_reader_phaser_init(struct hdr_writer_reader_phaser* p) { if (0 == p) { return EINVAL; } p->start_epoch = 0; p->even_end_epoch = 0; p->odd_end_epoch = INT64_MIN; p->reader_mutex = malloc(sizeof(pthread_mutex_t)); if (!p->reader_mutex) { return ENOMEM; } int rc = pthread_mutex_init(p->reader_mutex, 0); if (0 != rc) { return rc; } return 0; } void hdr_writer_reader_phaser_destory(struct hdr_writer_reader_phaser* p) { pthread_mutex_destroy(p->reader_mutex); } int64_t hdr_phaser_writer_enter(struct hdr_writer_reader_phaser* p) { return __atomic_add_fetch(&p->start_epoch, 1, 5); } void hdr_phaser_writer_exit( struct hdr_writer_reader_phaser* p, int64_t critical_value_at_enter) { int64_t* end_epoch = (critical_value_at_enter < 0) ? &p->odd_end_epoch : &p->even_end_epoch; __atomic_add_fetch(end_epoch, 1, 5); } void hdr_phaser_reader_lock(struct hdr_writer_reader_phaser* p) { pthread_mutex_lock(p->reader_mutex); } void hdr_phaser_reader_unlock(struct hdr_writer_reader_phaser* p) { pthread_mutex_unlock(p->reader_mutex); } void hdr_phaser_flip_phase( struct hdr_writer_reader_phaser* p, int64_t sleep_time_ns) { int64_t start_epoch = _hdr_phaser_get_epoch(&p->start_epoch); bool next_phase_is_even = (start_epoch < 0); int64_t initial_start_value; if (next_phase_is_even) { initial_start_value = 0; _hdr_phaser_set_epoch(&p->even_end_epoch, initial_start_value); } else { initial_start_value = INT64_MIN; _hdr_phaser_set_epoch(&p->odd_end_epoch, initial_start_value); } int64_t start_value_at_flip = _hdr_phaser_reset_epoch(&p->start_epoch, initial_start_value); bool caught_up = 0; do { int64_t* end_epoch = next_phase_is_even ? &p->odd_end_epoch : &p->even_end_epoch; caught_up = _hdr_phaser_get_epoch(end_epoch) == start_value_at_flip; if (!caught_up) { if (sleep_time_ns == 0) { sched_yield(); } else { usleep(sleep_time_ns / 1000); } } } while (!caught_up); }
0
#include <pthread.h> struct foo* fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo* f_next; int f_id; }; struct foo* foo_alloc(int id) { struct foo *fp; int idx; if((fp = (struct foo*)malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo* fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo* foo_find(int id) { struct foo* fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if(fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo* fp) { struct foo* tfp; int idx; pthread_mutex_lock(&hashlock); if(--fp->f_count == 0) { idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t fumatori; pthread_cond_t nfumatori; int occupatiS1_nf; int occupatiS2_f; int occupatiS2_nf; int fumatoriAttesa; int nfumatoriAttesa; } sala; sala S; void nfumatori_entra(sala *s, int *sala) { int i; pthread_mutex_lock(&s->mutex); while ( 3 - s->occupatiS1_nf < 1 && (2 - (s->occupatiS2_nf + s->occupatiS2_f) < 1 || s->occupatiS2_f != 0)) { s->nfumatoriAttesa++; printf("Non fumatori sospesi (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); pthread_cond_wait(&(s->nfumatori), &(s->mutex)); s->nfumatoriAttesa--; printf("Non fumatori risvegliato (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); } if (3 - s->occupatiS1_nf > 0) { s->occupatiS1_nf++; *sala = 1; } else { s->occupatiS2_nf++; *sala = 2; } printf("Gruppo non fumatori entrato (sala: %d) (sala1 liberi: %d - sala2 liberi: %d)\\n",*sala,3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); if (s->nfumatoriAttesa > 0) pthread_cond_signal (&(s->nfumatori)); else if (s->fumatoriAttesa > 0) pthread_cond_signal (&(s->fumatori)); pthread_mutex_unlock(&s->mutex); } void nfumatori_esce(sala *s, int sala) { int i; pthread_mutex_lock(&s->mutex); if (sala == 1) s->occupatiS1_nf--; else s->occupatiS2_nf--; printf("Non fumatori usciti da sala %d (sala1 liberi: %d - sala2 liberi: %d)\\n",sala,3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); if (s->nfumatoriAttesa > 0) pthread_cond_signal (&(s->nfumatori)); else if (s->fumatoriAttesa > 0) pthread_cond_signal (&(s->fumatori)); pthread_mutex_unlock(&s->mutex); } void fumatori_entra(sala *s) { int i, stop = 0; pthread_mutex_lock(&s->mutex); while ( s->nfumatoriAttesa > 0 || s->occupatiS2_nf > 0 || 2 - (s->occupatiS2_nf + s->occupatiS2_f) < 1) { s->fumatoriAttesa++; printf("Fumatori sospesi (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); pthread_cond_wait(&(s->fumatori), &(s->mutex)); s->fumatoriAttesa--; printf("Fumatori risvegliato (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); } s->occupatiS2_f++; printf("Fumatori entrati in S2 (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); if (s->fumatoriAttesa > 0) pthread_cond_signal (&(s->fumatori)); pthread_mutex_unlock(&s->mutex); } void fumatori_esce(sala *s) { int i; pthread_mutex_lock(&s->mutex); s->occupatiS2_f--; printf("Fumatori usciti da S2 (sala1 liberi: %d - sala2 liberi: %d)\\n",3 -s->occupatiS1_nf,2 -(s->occupatiS2_nf+s->occupatiS2_f)); if (s->nfumatoriAttesa > 0) pthread_cond_signal (&(s->nfumatori)); else if (s->fumatoriAttesa > 0) pthread_cond_signal (&(s->fumatori)); pthread_mutex_unlock(&s->mutex); } void *thread_nfumatori(void * arg) { int sala; sleep(1); nfumatori_entra(&S, &sala); sleep(1); nfumatori_esce(&S, sala); pthread_exit(0); } void *thread_fumatori(void * arg) { sleep(1); fumatori_entra(&S); sleep(1); fumatori_esce(&S); pthread_exit(0); } int main () { pthread_t fumatori[4], nfumatori[5]; int i; memset (&S, 0, sizeof(sala) ); pthread_mutex_init(&S.mutex, 0); pthread_cond_init (&S.fumatori,0); pthread_cond_init (&S.nfumatori,0); for (i = 0; i < 4; i++) pthread_create (&fumatori[i], 0, thread_fumatori, 0); for (i = 0; i < 5; i++) pthread_create (&nfumatori[i], 0, thread_nfumatori, 0); for (i = 0; i < 4; i++) pthread_join (fumatori[i], 0); for (i = 0; i < 5; i++) pthread_join (nfumatori[i], 0); return 0; }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc,condp; int buffer = 0; void *producer(void *ptr) { int i; for(i = 1; i<=100000000;i++) { pthread_mutex_lock(&the_mutex); while(buffer !=0) pthread_cond_wait(&condp, &the_mutex); buffer=i; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { int i; for(i = 1; i<=100000000; i++) { pthread_mutex_lock(&the_mutex); while(buffer == 0) pthread_cond_wait(&condc, &the_mutex); buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&the_mutex,0); pthread_cond_init(&condc,0); pthread_cond_init(&condp,0); pthread_create(&con,0,consumer,0); pthread_create(&pro,0,producer,0); pthread_join(pro,0); pthread_join(con,0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t m[6]; void *th(void *arg) { unsigned id = (unsigned long) arg; int i = id; int j = 1; while (i < 6 && j < 4) { pthread_mutex_lock(&m[i]); i+=j; j++; } while (i > id) { j--; i-=j; pthread_mutex_unlock(&m[i]); } return 0; } int main() { pthread_t ids[9]; for (int i = 0; i < 6; i++) { pthread_mutex_init(&m[i], 0); } for (int i = 0; i < 9; i++) { pthread_create(&ids[i], 0, th, (void*) (long) i); } for (int i = 0; i < 9; i++) { pthread_join(ids[i],0); } return 0; }
0
#include <pthread.h> _dataType data; struct _node* next; }node,*nodep,**nodepp; nodep head = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; nodep buyNode(_dataType val) { nodep tmp = (nodep)malloc(sizeof(node)); if(tmp!= 0) { tmp->data = val; tmp->next = 0; return tmp; } return 0; } void init(nodepp head) { *head = buyNode(0); } void push_list(nodep head,_dataType val) { nodep tmp = buyNode(val); tmp->next = head->next; head->next = tmp; } int pop_list(nodep head,_dataType_p pval) { if(0 == head->next) return -1; nodep del = head->next; *pval = del->data; head->next = del->next; free(del); return 0; } void* product(void* arg) { _dataType i = 0; while(1) { sleep(1); pthread_mutex_lock(&mutex); push_list(head,i++); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } pthread_exit((void *)1); } void* consumer(void *arg) { _dataType val = 0; while(1){ sleep(1); pthread_mutex_lock(&mutex); if(pop_list(head,&val) == -1) pthread_cond_wait(&cond,&mutex); printf("data:%d\\n",val); pthread_mutex_unlock(&mutex); } pthread_exit((void *)1); } int main() { pthread_t tid1,tid2; init(&head); pthread_create(&tid1,0,product,0); pthread_create(&tid2,0,consumer,0); pthread_join(tid1,0); pthread_join(tid2,0); free(head); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> long points_per_runner; long daire_ici; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct point { float x; float y; }; long thread_basina_iterasyonu_hesapla(long iterasyon_sayisi, int thread_sayisi) { return (iterasyon_sayisi / thread_sayisi); } int iceride_mi(struct point p1) { if (((p1.x * p1.x) + (p1.y * p1.y)) < 1) { return 1; } } void* runner(void* arg) { long daire_ici_thread = 0; struct point p1; long i = 0; unsigned int seed = rand(); for (i; i < points_per_runner; i++) { p1.x = rand_r(&seed) / ((double) 32767 + 1); p1.y = rand_r(&seed) / ((double) 32767 + 1); if (iceride_mi(p1) == 1) { daire_ici_thread++; } } pthread_mutex_lock(&mutex); daire_ici = daire_ici + daire_ici_thread; printf("daire_icine_du$en_nokta_sayisi= %lu \\n", daire_ici); pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { pthread_t *threads; clock_t begin, end; begin = clock(); clock_t tic = clock(); if (argc != 3) { printf("dogru kullanim:<iterasyon sayisi> <thread sayisi> \\n"); exit(1); } long iterasyon_sayisi = atol(argv[1]); printf("\\n \\niterasyon sayisi: %lu \\n", iterasyon_sayisi); int thread_sayisi = atoi(argv[2]); int NTHREADS = thread_sayisi; printf("NTHREADS: %d \\n", NTHREADS); points_per_runner = thread_basina_iterasyonu_hesapla(iterasyon_sayisi, thread_sayisi); printf("points per runner: %lu \\n", points_per_runner); threads = malloc(sizeof(pthread_t) * NTHREADS); int i; for (i = 0; i < NTHREADS; i++) { pthread_create(&threads[i], 0, runner, 0); } for (i = 0; i < NTHREADS; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); free(threads); printf("\\n|||||||||||||||||||||||Pi: %f\\n", (4. * (double) daire_ici) / ((double) points_per_runner * NTHREADS)); clock_t toc = clock(); printf("------->Elapsed: %f seconds\\n \\n", (double) (toc - tic) / CLOCKS_PER_SEC / NTHREADS); return 0; }
0
#include <pthread.h> void *pth_functionProducer(); void *pth_functionConsumer(void *); int count=0; int fp; pthread_mutex_t Rmutex; { off_t offset; char data[4096]; }NODE; struct BUF { int flag; NODE *node; }buf[10]; int isEmpty(); int isFull(); int main(int argc,char *argv[]) { int err; int index=0; int m; void *pRslt=0; for(m=0;m<10;m++) { buf[m].flag=0; } pthread_t pthR_t; pthread_t pthW_t[2]; if((fp=open(argv[1],O_RDONLY))<0) { printf("can't open file %s.\\n",argv[1]); } struct sockaddr_in server_addr; bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons(INADDR_ANY); server_addr.sin_port = htons(7754); int server_socket = socket(AF_INET,SOCK_STREAM,0); if( server_socket < 0) { printf("Create Socket Failed!"); exit(1); } if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))) { printf("Server Bind Port : %d Failed!", 7754); exit(1); } if ( listen(server_socket, 10) ) { printf("Server Listen Failed!"); exit(1); } if(pthread_mutex_init(&Rmutex,0)!=0) { printf("create mutex failed!\\n"); pthread_mutex_destroy(&Rmutex); exit(0); } if((err=pthread_create(&pthR_t,0,pth_functionProducer,0))!=0) { printf("Create Producer Thread %d Failed . exit !\\n",err); exit(0); } while(1) { pthread_t pthC; int new_server_socket = accept(server_socket,0,0); if (new_server_socket< 0) { perror("accept"); continue; } if((err=pthread_create(&pthC,0,pth_functionConsumer,(void*)new_server_socket))!=0) { printf("Create Consumer Thread Failed . exit !\\n"); exit(0); } if((err=pthread_join(pthC,pRslt))!=0) { printf("Can not join Consumer Thread .exit"); exit(0); } else { printf("Consumer Thread %d exit.!\\n",(int)pRslt); } } if((err=pthread_join(pthR_t,0))!=0) { printf("Can not join Producer Thread . exit\\n"); exit(0); } else { printf("Producer Thread exit.!\\n" ); } pthread_mutex_destroy(&Rmutex); close(server_socket); close(fp); return 0; } int isEmpty() { int flag; int i; for(i=0;i<10;i++) { if(buf[i].flag==0) { flag=1; break; } } if(flag) { return 1; } else { return 0; } } int isFull() { int flag; int i; for(i=0;i<10;i++) { if(buf[i].flag==1) { flag=1; break; } } if(flag) { return 1; } else { return 0; } } void * pth_functionProducer() { int i; printf("Producer Thread Create !\\n"); while(1) { if(isEmpty()) { for(i=0;i<10;i++) { if(buf[i].flag==0) { NODE *node; node=(NODE *)malloc(sizeof(NODE)); if(read(fp,node->data,sizeof(node->data))>0) { node->offset=count*4096; count++; pthread_mutex_lock(&Rmutex); buf[i].flag=1; buf[i].node=node; pthread_mutex_unlock(&Rmutex); } else { goto p1; } } } } } p1: printf("du jie shu"); return 0; } void * pth_functionConsumer(void * arg) { int socket; socket = (int)arg; int i; printf("Consumer Thread Create !\\n"); while(1) { if(isFull()) { for(i=0;i<10;i++) { pthread_mutex_lock(&Rmutex); if(buf[i].flag==1) { buf[i].flag=0; if(send(socket,buf[i].node,4100,0)<0) { printf("Send File is Failed\\n"); break; } free(buf[i].node); } pthread_mutex_unlock(&Rmutex); close(socket); break; } } usleep(1); if(isEmpty()) { close(socket); break; } } return arg; }
1
#include <pthread.h> { int job; struct jobnode* next; }JOB; JOB *head=0,*tail=0,*new_job,*traverse; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void *job_checking(void *arg) { for(;traverse!=0;) { pthread_mutex_lock(&mutex); printf("Job %d got checked by thread id: %d.\\n",traverse->job,(int)pthread_self()); pthread_mutex_unlock(&mutex); traverse=traverse->next; sleep(2); } } void create_job_queue(JOB* head) { int i,j; head=(JOB*)malloc(sizeof(JOB)); head->job=1; tail=head; traverse=head; tail->next=0; for(i=0,j=2;i<4;i++,j++) { new_job=(JOB*)malloc(sizeof(JOB)); new_job->job=j; tail->next=new_job; tail=new_job; tail->next=0; } } int main(int argc,char **argv) { int i; create_job_queue(head); pthread_t thread_id[4]; for(i=0;i<4;i++) pthread_create(&thread_id[i],0,job_checking,0); for(i=0;i<4;i++) pthread_join(thread_id[i],0); return 0; }
0
#include <pthread.h> int g_signaled = 0; pthread_mutex_t g_lock; pthread_cond_t g_cond; void *wait(void *data) { pthread_mutex_lock(&g_lock); while (g_signaled == 0) { printf("%lu wait cond\\n", pthread_self()); pthread_cond_wait(&g_cond, &g_lock); } pthread_mutex_unlock(&g_lock); printf("%lu bang!\\n", pthread_self()); return 0; } void *signal(void *data) { printf("sleep for a while...\\n"); pthread_mutex_lock(&g_lock); g_signaled = 1; pthread_mutex_unlock(&g_lock); printf("send out signal!\\n"); pthread_cond_broadcast(&g_cond); return 0; } int main(int argc, char **argv) { pthread_mutex_init(&g_lock, 0); pthread_cond_init(&g_cond, 0); const int nThreads = 5; pthread_t workers[nThreads]; int i; pthread_create(&workers[0], 0, wait, 0); pthread_create(&workers[1], 0, wait, 0); pthread_create(&workers[2], 0, wait, 0); pthread_create(&workers[3], 0, wait, 0); pthread_create(&workers[4], 0, signal, 0); qthread_hibernate_thread(0); for (i = 0; i < nThreads; i++) pthread_join(workers[i], 0); return 0; }
1
#include <pthread.h> int count_in=0,count_out=0; int dist_count[2]; pthread_mutex_t tunnel_in = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t tunnel_out = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dist[2] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}; int sem[2]; void in_tunnel(int type) { pthread_mutex_lock(&tunnel_in); printf("Masina din %d intra in tunel\\n",type); count_in++; pthread_mutex_lock(&dist[type]); dist_count[type]--; pthread_mutex_unlock(&dist[type]); pthread_mutex_unlock(&tunnel_in); } void out_tunnel(int type) { pthread_mutex_lock(&tunnel_out); printf("Masina din %d iese din tunel\\n",type); count_out++; pthread_mutex_unlock(&tunnel_out); } void *car(void *type) { int car_type = *(int*)type; free(type); pthread_mutex_lock(&dist[car_type]); dist_count[car_type]++; pthread_mutex_unlock(&dist[car_type]); sleep(5); while(sem[car_type] == 0) {;} in_tunnel(car_type); sleep(5); out_tunnel(car_type); return 0; } void *control_center(void *arg) { int timer; while(1) { timer = 0; count_in = 0; count_out = 0; printf("Semaforul din stanga se face verde\\n"); sem[0] = 1; sem[1] = 0; while(dist_count[1] == 0){;} while(!(dist_count[0] <5 && dist_count[1] >= 5) && count_in < 3 && (++timer)<1000000){;} printf("Semaforul din stanga se face rosu\\n"); sem[0] = 0; sleep(3); while(count_out <count_in){;} count_in = 0; count_out = 0; printf("Semaforul din dreapta se face verde\\n"); sem[1] = 1; timer = 0; while(dist_count[0] == 0){;} while(!(dist_count[0] >= 5 && dist_count[1] < 5) && count_in < 3 && (++timer)<1000000){;} printf("Semaforul din dreapta se face rosu\\n"); sem[1] = 0; timer = 0; sleep(3); while(count_out < count_in){;} } } int main() { pthread_t cars[100],control; srand(time(0)); pthread_create(&control,0,control_center,0); for(int i = 0; i < 100; i++) { int *x = (int*)malloc (sizeof(int)); *x = rand()%2; pthread_create(&cars[i],0,car,x); } for(int i = 0; i < 100; i++) { pthread_join(cars[i],0); } pthread_join(control,0); return 0; }
0
#include <pthread.h> { unsigned char status; char data[1024]; }Block_Info; static int initindicator = 0; pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER; Block_Info memory_block_arr[2]; int init() { memset(memory_block_arr, 0, 2*1024); } char * mymalloc(size) { int lindex; if(size> 1024) { return (0); } pthread_mutex_lock(&gmutex); if (initindicator == 0) { init(); initindicator = 1; } pthread_mutex_unlock(&gmutex); for(lindex = 0; lindex< 2; lindex++) { pthread_mutex_lock(&gmutex); if(0 == memory_block_arr[lindex].status) { memory_block_arr[lindex].status = 1; pthread_mutex_unlock(&gmutex); return((char *)&memory_block_arr[lindex].data); } else { if(lindex == (2 - 1)) { pthread_mutex_unlock(&gmutex); return(0); } } pthread_mutex_unlock(&gmutex); } } void myfree(char * address) { int lindex; for(lindex = 0; lindex< 2; lindex++) { pthread_mutex_lock(&gmutex); if(address == (char *)&memory_block_arr[lindex].data) memory_block_arr[lindex].status = 0; pthread_mutex_unlock(&gmutex); } }
1
#include <pthread.h> static pthread_key_t g_tid_key; static pthread_mutex_t g_thread_id_lock = PTHREAD_MUTEX_INITIALIZER; static uint32_t g_next_tid = 0; void unique_tid(void) { pthread_mutex_lock(&g_thread_id_lock); if (g_next_tid != 0) { pthread_mutex_unlock(&g_thread_id_lock); return; } if (pthread_key_create(&g_tid_key, 0)) abort(); g_next_tid = 1; pthread_mutex_unlock(&g_thread_id_lock); } uint32_t get_tid(void) { uint32_t tid; if (g_next_tid == 0) { unique_tid(); } tid = (uint32_t)(uintptr_t)pthread_getspecific(g_tid_key); if (tid == 0) { pthread_mutex_lock(&g_thread_id_lock); tid = g_next_tid++; if (tid == 0xffffffff) abort(); pthread_mutex_unlock(&g_thread_id_lock); if (pthread_setspecific(g_tid_key, (void*)(uintptr_t)tid)) abort(); } return tid; }
0
#include <pthread.h> int g_itemnum; struct { pthread_mutex_t mutex; int buff[(100000)]; int nindex; int nvalue; } shared; void* producer(void*); void* consumer(void*); int main(void) { int i; int threadnum, threadcount[(10)]; pthread_t tid_producer[(10)], tid_consumer; g_itemnum = (100000); threadnum = (10); pthread_setconcurrency(threadnum); for (i = 0; i < threadnum; ++i) { threadcount[i] = 0; if (0 != pthread_create(&tid_producer[i], 0, producer, (void*)&threadcount[i])) { printf("pthread_create error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] created, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } for (i = 0; i < threadnum; ++i) { if (0 != pthread_join(tid_producer[i], 0)) { printf("pthread_join error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] done, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } if (0 != pthread_create(&tid_consumer, 0, consumer, 0)) { printf("pthread_create error consumer\\n"); } printf("consumer: thread[%lu] created\\n", tid_consumer); if (0 != pthread_join(tid_consumer, 0)) { printf("pthread_join error consumer\\n"); } printf("consumer: thread[%lu] done\\n", tid_consumer); exit(0); } void* producer(void *arg) { for (;;) { if (shared.nindex >= g_itemnum) { return 0; } pthread_mutex_lock(&shared.mutex); shared.buff[shared.nindex] = shared.nvalue; shared.nindex++; shared.nvalue++; pthread_mutex_unlock(&shared.mutex); *((int*)arg) += 1; } return 0; } void* consumer(void *arg) { int i; for (i = 0; i < g_itemnum; ++i) { if (shared.buff[i] != i) { printf("error: buff[%d] = %d\\n", i, shared.buff[i]); } } return 0; }
1
#include <pthread.h> extern struct point p[MAX_POINTS]; extern struct point u[MAX_CENTERS]; extern int c[MAX_POINTS]; extern int iters; extern struct global_cluster cal_centre; extern pthread_mutex_t glob_clust_lock; extern pthread_barrier_t thrd_bar; void *k_means(void *parameter) { int i = 0, j = 0; double min_dist; double dist; struct thread_params *params = (struct thread_params *)parameter; double x_sum[params->num_clusters]; double y_sum[params->num_clusters]; unsigned long clust_size[params->num_clusters]; for(i = 0; i < params->num_clusters; i++) { x_sum[i] = 0; y_sum[i] = 0; clust_size[i] = 0; } while(iters != 0) { for(i = params->start_point; i < params->end_point; i++) { min_dist = DBL_MAX; for(j = 0; j < params->num_clusters; j++) { dist = ( (u[j].x - p[i].x) * (u[j].x - p[i].x) + (u[j].y - p[i].y) * (u[j].y - p[i].y) ); if(dist < min_dist) { min_dist = dist; c[i] = j; } } x_sum[c[i]] += p[i].x; y_sum[c[i]] += p[i].y; clust_size[c[i]] += 1; } pthread_mutex_lock(&glob_clust_lock); for(j = 0; j < params->num_clusters; j++) { cal_centre.p[j].x += x_sum[j]; cal_centre.p[j].y += y_sum[j]; cal_centre.clust_size[j] += clust_size[j]; x_sum[j] = 0; y_sum[j] = 0; clust_size[j] = 0; } cal_centre.thd_cmpt++; if(cal_centre.thd_cmpt == params->thread_count) { for(j = 0; j < params->num_clusters; j++) { if(cal_centre.clust_size[j] > 0) { u[j].x = cal_centre.p[j].x / (double)cal_centre.clust_size[j]; u[j].y = cal_centre.p[j].y / (double)cal_centre.clust_size[j]; } else { u[j] = random_center(p); } cal_centre.p[j].x = 0; cal_centre.p[j].y = 0; cal_centre.clust_size[j] = 0; } iters--; cal_centre.thd_cmpt = 0; } pthread_mutex_unlock(&glob_clust_lock); pthread_barrier_wait(&thrd_bar); } return 0; }
0
#include <pthread.h> void *Tackle(void *Dummy) { extern pthread_cond_t Snap; extern pthread_mutex_t Mutex; pthread_mutex_lock(&Mutex); printf("Waiting for the snap\\n"); pthread_cond_wait(&Snap,&Mutex); pthread_mutex_unlock(&Mutex); printf("Tackle!!\\n"); return(0); } int main(int argc,char *argv[]) { extern pthread_cond_t Snap; extern pthread_mutex_t Mutex; int Index; pthread_t NewThread; pthread_cond_init(&Snap,0); pthread_mutex_init(&Mutex,0); for (Index=0;Index<atoi(argv[1]);Index++) { if (pthread_create(&NewThread,0,Tackle,0) != 0) { perror("Creating thread"); exit(1); } if (pthread_detach(NewThread) != 0) { perror("Detaching thread"); exit(1); } } fgetc(stdin); pthread_cond_broadcast(&Snap); printf("Exiting the main program, leaving the threads running\\n"); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t lock; pthread_mutex_t lock2; int value; int value2; sem_t sem; void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(lock)); value = value + *v2; pthread_mutex_unlock(&(lock)); sem_post(&sem); } void *functionWithOtherCriticalSection(int* v2) { pthread_mutex_lock(&(lock2)); value2 = value2 + *v2; pthread_mutex_unlock(&(lock2)); sem_post(&sem); } void *functionWithMultilockCriticalSection(int* v2) { pthread_mutex_lock(&(lock)); pthread_mutex_lock(&(lock2)); value = value2 + *v2; pthread_mutex_unlock(&(lock)); pthread_mutex_unlock(&(lock2)); sem_post(&sem); } void *functionWithReadingCriticalSection(int* v2) { pthread_mutex_lock(&(lock)); printf("%d\\n", value); pthread_mutex_unlock(&(lock)); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); value = 0; value2 = 0; int v2 = 1; pthread_mutex_init((&(lock)), 0); pthread_mutex_init((&(lock2)), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithOtherCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_create (&thread1,0,functionWithMultilockCriticalSection,&v2); pthread_create (&thread2,0,functionWithReadingCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(lock)); pthread_mutex_destroy(&(lock2)); sem_destroy(&sem); printf("%d\\n", value); printf("%d\\n", value2); return 0; }
0
#include <pthread.h> int queue[10 + 1]; int r = 0; int f = 0; int over = 0; pthread_mutex_t m; pthread_cond_t c; void enqueue(int n) { queue[++r] = n; } int dequeue() { return queue[++f]; } int q_empty() { return f == r; } void* producer(void* p) { int n = *(int*)p; for(int i = 0; i < n; ++i) { sleep(2); pthread_mutex_lock(&m); enqueue(i * i); pthread_cond_signal(&c); pthread_mutex_unlock(&m); } pthread_mutex_lock(&m); over = 1; pthread_mutex_unlock(&m); } void* consumer() { int res; pthread_mutex_lock(&m); while(!over || ! q_empty()) { pthread_mutex_unlock(&m); pthread_mutex_lock(&m); while(q_empty()) { pthread_cond_wait(&c, &m); } res = dequeue(); pthread_mutex_unlock(&m); printf("res : %d\\n", res); } } int main() { int n = 10; pthread_mutex_init(&m, 0); pthread_cond_init(&c, 0); pthread_t t1; pthread_t t2; pthread_create(&t1, 0, producer, (void*)&n); pthread_create(&t2, 0, consumer, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_exit(0); }
1
#include <pthread.h> void hello(); void world(); void again(); pthread_mutex_t mutex; pthread_cond_t done_hello, done_world; int done = 0; int main (int argc, char *argv[]){ pthread_t tid_hello, tid_world, tid_again; pthread_mutex_init(&mutex, 0); pthread_cond_init(&done_hello, 0); pthread_cond_init(&done_world, 0); pthread_create(&tid_hello, 0, (void*)&hello, 0); pthread_create(&tid_world, 0, (void*)&world, 0); pthread_create(&tid_again, 0, (void*)&again, 0); pthread_join(tid_hello, 0); pthread_join(tid_world, 0); pthread_join(tid_again, 0); printf("\\n"); return 0; } void hello() { pthread_mutex_lock(&mutex); printf("hello "); fflush(stdout); done = 1; pthread_cond_signal(&done_hello); pthread_mutex_unlock(&mutex); return ; } void world() { pthread_mutex_lock(&mutex); while(done != 1) pthread_cond_wait(&done_hello, &mutex); printf("world "); fflush(stdout); done = 2; pthread_cond_signal(&done_world); pthread_mutex_unlock(&mutex); return ; } void again() { pthread_mutex_lock(&mutex); while(done != 2) pthread_cond_wait(&done_world, &mutex); printf("again"); fflush(stdout); pthread_mutex_unlock(&mutex); return ; }
0
#include <pthread.h> pthread_t t[7]; pthread_mutex_t mtx[10]; int sum_rest[10]; void * doIt(void *arg) { int i; for(i = 0; i < 100; ++ i) { int x = rand() % 10000; printf("Thread mod: %d, nr: %d\\n", x % 10, x); pthread_mutex_lock(&mtx[x % 10]); sum_rest[x % 10] += x; pthread_mutex_unlock(&mtx[x % 10]); } return 0; } int main() { srand(time(0)); int i; for(i = 0; i < 10; ++ i) pthread_mutex_init(&mtx[i], 0); for(i = 0; i < 7; ++ i) pthread_create(&t[i], 0, doIt, 0); for(i = 0; i < 7; ++ i) pthread_join(t[i], 0); for(i = 0; i < 10; ++ i) pthread_mutex_destroy(&mtx[i]); printf("Father:\\n"); for(i = 0; i < 10; ++ i) printf("%d ", sum_rest[i]); printf("\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond_lei; pthread_cond_t cond_esc; int escritoras = 0, leitoras = 0, filaEsc = 0; { int contador; int idThread; } File; File a; void init_leitora(){ pthread_mutex_lock(&mutex); while(escritoras > 0 || filaEsc > 0){ pthread_cond_wait(&cond_lei, &mutex); } leitoras++; pthread_mutex_unlock(&mutex); } void exit_leitora(){ pthread_mutex_lock(&mutex); leitoras--; if(leitoras == 0 || filaEsc > 0) pthread_cond_signal(&cond_esc); pthread_mutex_unlock(&mutex); } void init_escritora(){ pthread_mutex_lock(&mutex); filaEsc++; while(escritoras>0){ pthread_cond_wait(&cond_esc, &mutex); } escritoras++; pthread_mutex_unlock(&mutex); } void exit_escritora(){ pthread_mutex_lock(&mutex); escritoras--; filaEsc--; pthread_cond_signal(&cond_esc); if(filaEsc == 0){ pthread_cond_broadcast(&cond_lei); } pthread_mutex_unlock(&mutex); } void *leitora(void * arg){ int tid = * (int *) arg; File aLocal; while(1){ printf("Eu sou a thread leitora: %d \\n", tid); init_leitora(); aLocal.contador = a.contador; aLocal.idThread = a.idThread; printf("Contador: %d \\n Gravado pela thread leitora %d \\n", aLocal.contador, aLocal.idThread); exit_leitora(); sleep(1); } pthread_exit(0); free(arg); } void *escritora(void *arg){ int tid = * (int *) arg; while(1){ printf("Eu sou a thread escritora: %d \\n", tid); init_escritora(); pthread_mutex_lock(&mutex); a.contador++; a.idThread = tid; pthread_mutex_unlock(&mutex); exit_escritora(); sleep(1); } pthread_exit(0); free(arg); } int main(int argc, char *argv[]){ int *pid, i; pthread_t threads[3 +3]; for(i=0; i<3; i++){ pid = (int*) malloc(sizeof(int)); *pid = i; pthread_create(&threads[i], 0, escritora, (void *) pid); } for(i=3; i<3 +3; i++){ pid = (int*) malloc(sizeof(int)); *pid = i; pthread_create(&threads[i], 0, leitora, (void *) pid); } for(i=0; i<3 +3; i++){ pthread_join(threads[i],0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_lei); pthread_cond_destroy(&cond_esc); free(pid); return 0; }
0
#include <pthread.h> struct gamelock { void* object; sem_t readOnly; sem_t modify; pthread_mutex_t atom; }; struct gamelock* gamelock_new(void* object) { struct gamelock* lock; lock = malloc(sizeof(struct gamelock)); if (lock == 0) { pok_exception_flag_memory_error(); return 0; } lock->object = object; sem_init(&lock->readOnly,0,10); sem_init(&lock->modify,0,1); pthread_mutex_init(&lock->atom,0); return lock; } void gamelock_free(struct gamelock* lock) { free(lock); } void gamelock_aquire(struct gamelock* lock) { sem_wait(&lock->modify); } void gamelock_release(struct gamelock* lock) { sem_post(&lock->modify); } void gamelock_up(struct gamelock* lock) { pthread_mutex_lock(&lock->atom); { int value; sem_getvalue(&lock->readOnly,&value); if (value == 10) { sem_wait(&lock->modify); sem_wait(&lock->readOnly); pthread_mutex_unlock(&lock->atom); return; } } pthread_mutex_unlock(&lock->atom); sem_wait(&lock->readOnly); } void gamelock_down(struct gamelock* lock) { pthread_mutex_lock(&lock->atom); { int value; sem_post(&lock->readOnly); sem_getvalue(&lock->readOnly,&value); if (value == 10) sem_post(&lock->modify); } pthread_mutex_unlock(&lock->atom); } int gamelock_compar(const struct gamelock* left,const struct gamelock* right) { long long int result = (long long int)left->object - (long long int)right->object; return result < 0 ? -1 : (result > 0 ? 1 : 0); } void pok_timeout(struct pok_timeout_interval* interval) { struct timespec ts; struct timespec before, after; clock_gettime(CLOCK_MONOTONIC,&before); ts.tv_sec = 0; ts.tv_nsec = interval->nseconds; nanosleep(&ts,0); clock_gettime(CLOCK_MONOTONIC,&after); interval->elapsed = ((uint64_t)1000000000 * (after.tv_sec - before.tv_sec) + (after.tv_nsec - before.tv_nsec)) / 1000000; } void pok_timeout_no_elapsed(struct pok_timeout_interval* interval) { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = interval->nseconds; nanosleep(&ts,0); }
1
#include <pthread.h> { int readers; int slots[10]; }mem_structure; mem_structure *stocklist; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t *stop_writers; int shmid; pthread_t my_threads[5 + 5]; int id[5 + 5]; void init() { sem_unlink("STOP_WRITERS"); stop_writers = sem_open("STOP_WRITERS", O_CREAT|O_EXCL, 0700, 1); shmid = shmget(IPC_PRIVATE, sizeof(mem_structure), IPC_CREAT|0700); stocklist = (mem_structure*) shmat(shmid, 0, 0); stocklist->readers = 0; } void terminate(int signo) { pthread_mutex_destroy(&mutex); sem_close(stop_writers); sem_unlink("STOP_WRITERS"); if (shmid >= 0) { shmctl(shmid, IPC_RMID, 0); } printf("Closing...\\n"); exit(0); } int get_stock_value() { return (1 + (int) (100.0 * rand() / (32767 + 1.0))); } int get_stock() { return (int) (rand() % 10); } void write_stock(int n_writer) { int stock = get_stock(); int stock_value = get_stock_value(); stocklist->slots[stock] = stock_value; fprintf(stderr, "Stock %d updated by BROKER %d to %d\\n", stock, n_writer, stock_value); } void* writer_code(void* n_writer) { int aux = *((int*) n_writer); int writer = aux; while(1) { pthread_mutex_lock(&mutex); sem_wait(stop_writers); write_stock(writer); sem_post(stop_writers); pthread_mutex_unlock(&mutex); sleep(1 + (int) (10.0 * rand() / (32767 + 1.0))); } pthread_exit(0); } void read_stock(int pos, int n_reader) { fprintf(stderr, "Stock %d read by client %d = %d.\\n", pos, n_reader, stocklist->slots[pos]); } void* reader_code(void* n_reader) { int aux = *((int*) n_reader); int reader = aux; while(1) { sem_wait(stop_writers); read_stock(get_stock(), reader); sem_post(stop_writers); sleep(1 + (int) (3.0 * rand() / (32767 + 1.0))); } pthread_exit(0); } void monitor() { struct sigaction act; act.sa_handler = terminate; act.sa_flags = 0; if ((sigemptyset(&act.sa_mask) == -1) || (sigaction(SIGINT, &act, 0) == -1)) perror("Failed to set SIGINT to handle Ctrl-C"); while(1){ sleep(5); printf("Still working...\\n"); } exit(0); } int main() { int i = 0; init(); for (i = 0; i < 5 + 5; i++) { id[i] = i; if (i%2 == 0) { pthread_create(&my_threads[i], 0, writer_code, &id[i]); } else { pthread_create(&my_threads[i], 0, reader_code, &id[i]); } } monitor(); exit(0); }
0
#include <pthread.h> pthread_mutex_t theMutex; pthread_cond_t theCond; int val; struct _buffer *next; } buffer; buffer *beginBuf; void* producer(void *args); void* consumer(void *args); void insert(int n); int get(); int getSize(buffer *buf); int isPrime(long unsigned int n); void printBuf(buffer *buf) { buffer *aux; int i; for (aux = buf, i =0; aux != 0; aux = aux->next, i++) printf("[%d] - Valor: %d\\n", i, aux->val); printf("\\n"); } int main(int argc, char const *argv[]) { int i, *id; pthread_t threads[4]; beginBuf = 0; pthread_mutex_init(&theMutex, 0); pthread_cond_init (&theCond, 0); for (i = 0; i < 4; i++) { id = (int *) malloc(sizeof(int)); if (!i) { *id = i; pthread_create(&threads[i], 0, producer, (void *) id); } else { *id = i - 1; pthread_create(&threads[i], 0, consumer, (void *) id); } } pthread_exit(0); return 0; } int getSize(buffer *buf) { int counter = 0; buffer *aux; aux = buf; while (aux != 0) { counter++; aux = aux->next; } return counter; } void insert(n) { buffer *aux; pthread_mutex_lock(&theMutex); while (getSize(beginBuf) > 5) { pthread_cond_wait(&theCond, &theMutex); } if (beginBuf != 0) { for (aux = beginBuf; aux->next != 0; aux = aux->next); aux->next = (buffer *) malloc(sizeof(buffer)); aux->next->val = n; aux->next->next = 0; } else { beginBuf = (buffer *) malloc(sizeof(buffer)); beginBuf->next = 0; beginBuf->val = n; } pthread_cond_signal(&theCond); pthread_mutex_unlock(&theMutex); } int get() { int val; buffer *aux; pthread_mutex_lock(&theMutex); while (getSize(beginBuf) == 0) pthread_cond_wait(&theCond, &theMutex); val = beginBuf->val; aux = beginBuf->next; free(beginBuf); beginBuf = aux; pthread_cond_signal(&theCond); pthread_mutex_unlock(&theMutex); return val; } void* producer(void *args) { int n[3] = {0, 1, 1}, i, *myId; insert(n[1]); insert(n[2]); myId = (int *) args; for (i = 3; i <= 25; i++) { n[0] = n[1] + n[2]; insert(n[0]); n[1] = n[2]; n[2] = n[0]; } printf("%d (Producer) - exiting...\\n", *myId); pthread_exit(0); } void* consumer(void *args) { int n, i, *myId; myId = (int *) args; for (i = *myId; i < 25; i += 4 - 1) { n = get(); printf("(%d) - %d: %s\\n", i, n, (isPrime(n))?"is prime":"is NOT prime"); } free(myId); printf("%d (Consumer) - exiting...\\n", *myId); pthread_exit(0); } int isPrime(long unsigned int n) { int i; if (n <= 1) return 0; if (n == 2) return 1; if (n%2 == 0) return 0; for(i = 3; i < sqrt(n) + 1; i += 2) { if (n % i == 0) return 0; } return 1; }
1
#include <pthread.h> pthread_t thread; int terminate; struct NWORKQUEUE *workqueue; struct NWORKER *prev; struct NWORKER *next; } nWorker; void (*job_function)(struct NJOB *job); void *user_data; struct NJOB *prev; struct NJOB *next; } nJob; struct NWORKER *workers; struct NJOB *waiting_jobs; pthread_mutex_t jobs_mtx; pthread_cond_t jobs_cond; } nWorkQueue; static void *ntyWorkerThread(void *ptr) { nWorker *worker = (nWorker*)ptr; while (1) { pthread_mutex_lock(&worker->workqueue->jobs_mtx); while (worker->workqueue->waiting_jobs == 0) { if (worker->terminate) break; pthread_cond_wait(&worker->workqueue->jobs_cond, &worker->workqueue->jobs_mtx); } if (worker->terminate) break; nJob *job = worker->workqueue->waiting_jobs; if (job != 0) { do { if (job->prev != 0) job->prev->next = job->next; if (job->next != 0) job->next->prev = job->prev; if (worker->workqueue->waiting_jobs == job) worker->workqueue->waiting_jobs = job->next; job->prev = job->next = 0; } while(0); } pthread_mutex_unlock(&worker->workqueue->jobs_mtx); if (job == 0) continue; job->job_function(job); } free(worker); pthread_exit(0); } int ntyThreadPoolCreate(nThreadPool *workqueue, int numWorkers) { if (numWorkers < 1) numWorkers = 1; memset(workqueue, 0, sizeof(nThreadPool)); pthread_cond_t blank_cond = PTHREAD_COND_INITIALIZER; memcpy(&workqueue->jobs_cond, &blank_cond, sizeof(workqueue->jobs_cond)); pthread_mutex_t blank_mutex = PTHREAD_MUTEX_INITIALIZER; memcpy(&workqueue->jobs_mtx, &blank_mutex, sizeof(workqueue->jobs_mtx)); int i = 0; for (i = 0;i < numWorkers;i ++) { nWorker *worker = (nWorker*)malloc(sizeof(nWorker)); if (worker == 0) { perror("malloc"); return 1; } memset(worker, 0, sizeof(nWorker)); worker->workqueue = workqueue; int ret = pthread_create(&worker->thread, 0, ntyWorkerThread, (void *)worker); if (ret) { perror("pthread_create"); free(worker); return 1; } do { worker->prev = 0; worker->next = worker->workqueue->workers; worker->workqueue->workers = worker; } while(0); } return 0; } void ntyThreadPoolShutdown(nThreadPool *workqueue) { nWorker *worker = 0; for (worker = workqueue->workers;worker != 0;worker = worker->next) { worker->terminate = 1; } pthread_mutex_lock(&workqueue->jobs_mtx); workqueue->workers = 0; workqueue->waiting_jobs = 0; pthread_cond_broadcast(&workqueue->jobs_cond); pthread_mutex_unlock(&workqueue->jobs_mtx); } void ntyThreadPoolQueue(nThreadPool *workqueue, nJob *job) { pthread_mutex_lock(&workqueue->jobs_mtx); do { job->prev = 0; job->next = workqueue->waiting_jobs; workqueue->waiting_jobs = job; } while(0); pthread_cond_signal(&workqueue->jobs_cond); pthread_mutex_unlock(&workqueue->jobs_mtx); } void king_counter(nJob *job) { int index = *(int*)job->user_data; printf("index : %d, selfid : %lu\\n", index, pthread_self()); free(job->user_data); free(job); } int main(int argc, char *argv[]) { nThreadPool pool; ntyThreadPoolCreate(&pool, 80); int i = 0; for (i = 0;i < 1000;i ++) { nJob *job = (nJob*)malloc(sizeof(nJob)); if (job == 0) { perror("malloc"); exit(1); } job->job_function = king_counter; job->user_data = malloc(sizeof(int)); *(int*)job->user_data = i; ntyThreadPoolQueue(&pool, job); } getchar(); printf("\\n"); }
0
#include <pthread.h> int main(int argc, char const *argv[]) { srand(time(0)); int i,tmp[P],err; err = pthread_mutex_init(&disp_mutex,0); assert(!err); for(i = 0;i < P;++i) { forkState[i] = 1; phil_cycles[i] = 0; err = pthread_mutex_init(&mutex[i],0); assert(!err); } for(i = 0;i < P;++i) { tmp[i] = i; int err = pthread_create(&philosopher[i],0,(void*)current_thread,(void*)&tmp[i]); assert(!err); } for(i = 0;i < P;++i) { pthread_join(philosopher[i],0); } for(i = 0;i < P;++i) { printf("Philosopher %d : %d\\n", i+1,phil_cycles[i]); } pthread_mutex_destroy(&disp_mutex); for(i = 0;i < P;++i) { pthread_mutex_destroy(&mutex[i]); } return 0; } void pickup_forks(int i) { pthread_mutex_lock(&mutex[i]); while(!forkState[i]); forkState[i] = 0; pthread_mutex_unlock(&mutex[i]); pthread_mutex_lock(&mutex[(i+1)%P]); while(!forkState[(i+1)%P]); forkState[(i+1)%P] = 0; pthread_mutex_unlock(&mutex[(i+1)%P]); } void return_forks(int i) { pthread_mutex_lock(&mutex[i]); forkState[i] = 1; pthread_mutex_unlock(&mutex[i]); pthread_mutex_lock(&mutex[(i+1)%P]); forkState[(i+1)%P] = 1; pthread_mutex_unlock(&mutex[(i+1)%P]); } bool display_count(int p) { bool end = 0; pthread_mutex_lock(&disp_mutex); if(total_cycles >= MAX_CYCLES) end = 1; pthread_mutex_unlock(&disp_mutex); return end; } void *current_thread(void *philosopher_number) { int p = *(int*)philosopher_number,delay; while(1) { printf("Philosopher %d waiting and trying to pickup forks.\\n",p+1); pickup_forks(p); delay = (rand()%3+1); printf("Philosopher %d is eating for %d seconds.\\n",p + 1, delay); sleep(delay); return_forks(p); delay = (rand()%3+1); printf("Philosopher %d is thinking for %d seconds.\\n",p + 1, delay); sleep(delay); phil_cycles[p]++; if(display_count(p)) break; } }
1
#include <pthread.h> enum { QUEUE_BUF_SIZE = 100000, }; int size; int tail; void **buf; } vector_t; int front; int tail; int max_size; void **cyclic_buf; } queue_cycl_t; vector_t *vector_init(int size) { vector_t *tmp = 0; tmp = (vector_t *)calloc(1, sizeof(vector_t)); if (tmp == 0) goto vector_init_err; tmp->buf = (void **)calloc(size, sizeof(void *)); if (tmp->buf == 0) goto vector_init_err; tmp->size = size; tmp->tail = 0; return tmp; vector_init_err: fprintf(stderr, "vector_init error\\n"); if (tmp) free(tmp->buf); free(tmp); exit(1); } int vector_push_back(vector_t *v, void *data) { if (v->tail == v->size) return 0; v->buf[v->tail++] = data; return 1; } void *vector_pop_back(vector_t *v) { return (v->tail == 0) ? 0: v->buf[(v->tail--) - 1]; } void vector_delete(vector_t *v) { free(v->buf); free(v); } queue_cycl_t *queue_init() { queue_cycl_t *tmp = 0; tmp = (queue_cycl_t *)calloc(1, sizeof(queue_cycl_t)); if (tmp == 0) goto queue_init_err; tmp->max_size = QUEUE_BUF_SIZE + 1; tmp->cyclic_buf = (void **)calloc(QUEUE_BUF_SIZE + 1, sizeof(void *)); if (tmp->cyclic_buf == 0) goto queue_init_err; return tmp; queue_init_err: fprintf(stderr, "queue_init error\\n"); if (tmp) free(tmp->cyclic_buf); free(tmp); exit(1); } int queue_size(queue_cycl_t *q) { return (q->tail >= q->front) ? (q->tail - q->front) : (q->max_size - q->front + q->tail); } int queue_is_full(queue_cycl_t *q) { return ((q->tail + 1) % q->max_size == q->front) ? 1 : 0; } int queue_is_empty(queue_cycl_t *q) { return (q->front == q->tail) ? 1 : 0; } int queue_enqueue(queue_cycl_t *q, void *data, int data_size) { if (queue_is_full(q)) return 0; q->cyclic_buf[q->tail] = data; q->tail = (q->tail + 1) % q->max_size; return 1; } void *queue_dequeue(queue_cycl_t *q) { void *tmp = 0; if (queue_is_empty(q)) return 0; tmp = q->cyclic_buf[q->front]; q->cyclic_buf[q->front] = 0; q->front = (q->front + 1) % q->max_size; return tmp; } vector_t *queue_dequeueall(queue_cycl_t *q) { int s = queue_size(q); vector_t *tmp = vector_init(s); void *data = 0; while ((data = queue_dequeue(q)) != 0) { if (!vector_push_back(tmp, data)) { queue_enqueue(q, data, 0); goto queue_dequeueall_err; } } return tmp; queue_dequeueall_err: fprintf(stderr, "[%s:%d] queue_dequeueall error\\n", __func__, 152); exit(1); } void queue_delete(queue_cycl_t *q) { free(q->cyclic_buf); free(q); } void queue_foreach(queue_cycl_t *q, void (*fnc)(void*)) { int tmp = q->front; while (tmp != q->tail) { fnc(q->cyclic_buf[tmp]); tmp = (tmp + 1) % q->max_size; } } void print_int(void *arg) { printf("%d ", *(int *)arg); } pthread_t therad; pthread_mutex_t m; pthread_cond_t cond; queue_cycl_t *q; } actor_t; void actor_send_to(actor_t *a, void *msg); void *sender(void *arg) { actor_t *receiver = (actor_t *)arg; int *msg = 0; for (int i = 0; i < 50; i++) { msg = (int *)calloc(1, sizeof(int)); *msg = i; actor_send_to(receiver, msg); } return 0; } int n_senders; void *actor_runner(void *arg) { actor_t *iam = (actor_t *)arg; int buf[50]; memset(buf, 0, sizeof(int) * 50); while (1) { pthread_mutex_lock(&iam->m); if (!queue_size(iam->q)) pthread_cond_wait(&iam->cond, &iam->m); vector_t *v = queue_dequeueall(iam->q); pthread_mutex_unlock(&iam->m); int *data = 0, exit = 0; while ((data = vector_pop_back(v)) != 0) { if (*data == -1) { exit = 1; } else { buf[*data]++; } free(data); } vector_delete(v); if (exit) break; } for (int i = 0; i < 50; i++) { if (buf[i] != n_senders) fprintf(stderr, "ERROR!!!!!!!!\\n"); } return 0; } actor_t * actor_init() { actor_t *tmp = 0; tmp = (actor_t *)calloc(1, sizeof(actor_t)); if (tmp == 0) goto actor_init_err; pthread_mutex_init(&tmp->m, 0); pthread_cond_init(&tmp->cond, 0); tmp->q = queue_init(); pthread_create(&tmp->therad, 0, actor_runner, tmp); return tmp; actor_init_err: fprintf(stderr, "[%s:%d] actor_init error\\n", __func__, 249); exit(1); } void actor_send_to(actor_t *a, void *msg) { pthread_mutex_lock(&a->m); queue_enqueue(a->q, msg, 0); pthread_cond_signal(&a->cond); pthread_mutex_unlock(&a->m); } void actor_finalize(actor_t *a) { pthread_join(a->therad, 0); queue_delete(a->q); pthread_mutex_destroy(&a->m); pthread_cond_destroy(&a->cond); free(a); } int main(int argc, char **argv) { actor_t *actor = 0; pthread_t *senders_id = 0; if (argc != 2) { fprintf(stderr, "[%s:%d] Start failed. A number of senders is not specified\\n", __func__, 278); exit(1); } n_senders = atoi(argv[1]); senders_id = (pthread_t *)calloc(n_senders, sizeof(pthread_t)); actor = actor_init(); for (int i = 0; i < n_senders; i++) { pthread_create(&senders_id[i], 0, sender, actor); } for (int i = 0; i < n_senders; i++) { pthread_join(senders_id[i], 0); } int *msg_ext = (int *)calloc(1, sizeof(int)); *msg_ext = -1; actor_send_to(actor, msg_ext); actor_finalize(actor); return 0; }
0
#include <pthread.h> const int LAST_CUSTOMER_ARRIVAL_TIME = 59; int customerCounter = 0; int (*queue)[10]; int lineFront[10]; pthread_mutex_t queueMutex; void* customer(void*); pthread_t* newCustomer(int sellerIndex) { pthread_t customerThreadID; pthread_attr_t customerAttr; pthread_attr_init(&customerAttr); int* id = malloc(sizeof(int)); *id = sellerIndex; pthread_create(&customerThreadID, &customerAttr, customer, id); return &customerThreadID; } void* customer(void* arg) { sleep(1 + rand() % LAST_CUSTOMER_ARRIVAL_TIME); int me = customerCounter++; int id = *((int*) arg); pthread_mutex_lock(&queueMutex); int i; for(i = 0; queue[i][id] != -1; i++) { } queue[i][id] = me; char event[99]; sprintf(event, "Customer %2d arrives (line %d, position %d)", me, id, i); printEvent(event); pthread_mutex_unlock(&queueMutex); } void initializeCustomerQueues(int maxCustomers) { pthread_mutex_init(&queueMutex, 0); queue = malloc(sizeof(int) * (maxCustomers + 1) * 10); int i; int j; for(i = 0; i < maxCustomers + 1; i++) { for(j = 0; j < 10; j++) { queue[i][j] = -1; } } for(i = 0; i < 10; i++) { lineFront[i] = 0; } } int getCustomer(int queueIndex) { pthread_mutex_lock(&queueMutex); int customerIndex = queue[lineFront[queueIndex]][queueIndex]; if(customerIndex != -1) { lineFront[queueIndex]++; } pthread_mutex_unlock(&queueMutex); return customerIndex; }
1
#include <pthread.h> pthread_mutex_t spoon[5]; void phil_init(int a, int* b, int* c) { *b=(a>0) ? a-1 : 5; *c=a; printf("Philosopher %d started\\n", a+1); return; } int check_If_Spoons_Are_Available(int a, int b, int c) { int sum=0; if(a&1) { sum = pthread_mutex_trylock(&spoon[c])==0 ? 0 : 10; sum += pthread_mutex_trylock(&spoon[b])==0 ? 0 : 1; } else { sum = pthread_mutex_trylock(&spoon[b])==0 ? 0 : 1; sum += pthread_mutex_trylock(&spoon[c])==0 ? 0 : 10; } return sum; } void Release_Spoons(int a, int b, int c) { if(a&1) { pthread_mutex_unlock(&spoon[b]); pthread_mutex_unlock(&spoon[c]); } else { pthread_mutex_unlock(&spoon[c]); pthread_mutex_unlock(&spoon[b]); } } void wait_for_others_to_finish(int a, int b ,int c, int d) { switch(a) { case 1: printf("Philosopher %d waiting since right spoon is unavailable\\n",b+1); pthread_mutex_lock(&spoon[c]); break; case 10: printf("Philosopher %d waiting since left spoon is unavailable\\n", b+1); pthread_mutex_lock(&spoon[d]); break; case 11: printf("Philosopher %d waiting since both spoons are unavailable\\n", b+1); if(a&1) { pthread_mutex_lock(&spoon[d]); pthread_mutex_lock(&spoon[c]); } else { pthread_mutex_lock(&spoon[d]); pthread_mutex_lock(&spoon[c]); } break; } return; } void Eat(int a) { printf("philosopher %d eating\\n", a+1); sleep(rand()%5); printf("philosopher %d finished eating\\n", a+1); } void philo(void * arg) { int back; int front; int tmp; int id=*((int*)arg); phil_init(id, &back, &front); while(1) { printf("philosopher %d thinking\\n", id+1); sleep(rand()%6); if((tmp=check_If_Spoons_Are_Available(id, back, front))!=0) wait_for_others_to_finish(tmp, id, back, front); Eat(id); Release_Spoons(*((int*)arg), back, front); } } int main(int argc, char* argv[]) { pthread_t S[5]; int *g; for(int i=0; i<5; i++) pthread_mutex_init(&spoon[i], 0); g=(int*)malloc(5*sizeof(int)); for(int i=0; i<5; i++) { g[i]=i; pthread_create(&S[i], 0, (void*)&philo,(void*)&g[i]); } pthread_join(S[0], 0); exit(0); }
0
#include <pthread.h> sem_t forks[5]; pthread_mutex_t mutex; void init ( ) { int i; for ( i = 0 ; i < 5 ; i++ ) sem_init(&forks[i],0,1); } void * philosopher ( void* arg ) { int* p = (int*)arg; int x = *p; while ( 1 ) { pthread_mutex_lock(&mutex); sem_wait(&forks[x]); sem_wait(&forks[(x+1)%5]); printf ( "the %dth philosopher having meal...\\n" , x ); sleep(1); sem_post(&forks[x]); sem_post(&forks[(x+1)%5]); pthread_mutex_unlock(&mutex); sleep(2); } } int main ( ) { init (); pthread_t id[5]; int tid[5]; int i; for ( i = 0 ; i < 5 ; i++ ) { tid[i] = i; pthread_create ( &id[i] , 0 , philosopher , &tid[i] ); } for ( i = 0 ; i < 5 ; i++ ) pthread_join ( id[i] , 0 ); }
1
#include <pthread.h> struct pp_thread_info { int *msgcount; pthread_mutex_t *mutex; pthread_cond_t *wait_cv; pthread_cond_t *signal_cv; char *msg; int modval; }; void * pp_thread(void *arg) { struct pp_thread_info *infop; int c; infop = arg; while (*infop->msgcount < 50) { pthread_mutex_lock(infop->mutex); while (*infop->msgcount % 2 != infop->modval) pthread_cond_wait(infop->wait_cv, infop->mutex); printf("%s\\n", infop->msg); c = *infop->msgcount; usleep(10); c = c + 1; *infop->msgcount = c; pthread_cond_signal(infop->signal_cv); pthread_mutex_unlock(infop->mutex); } return (0); } int main(void) { int msgcount; pthread_cond_t ping_cv, pong_cv; pthread_mutex_t mutex; pthread_t ping_id1, pong_id1; pthread_t ping_id2, pong_id2; struct pp_thread_info ping, pong; msgcount = 0; if (pthread_mutex_init(&mutex, 0) != 0) { fprintf(stderr, "Pingpong: Mutex init failed %s\\n", strerror(errno)); exit(1); } if (pthread_cond_init(&ping_cv, 0) != 0) { fprintf(stderr, "Pingpong: CV init failed %s\\n", strerror(errno)); exit(1); } if (pthread_cond_init(&pong_cv, 0) != 0) { fprintf(stderr, "Pingpong: CV init failed %s\\n", strerror(errno)); exit(1); } ping.msgcount = &msgcount; ping.mutex = &mutex; ping.wait_cv = &ping_cv; ping.signal_cv = &pong_cv; ping.msg = "ping"; ping.modval = 0; pong.msgcount = &msgcount; pong.mutex = &mutex; pong.wait_cv = &pong_cv; pong.signal_cv = &ping_cv; pong.msg = "pong"; pong.modval = 1; if ((pthread_create(&ping_id1, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id1, 0, &pp_thread, &pong) != 0) || (pthread_create(&ping_id2, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id2, 0, &pp_thread, &pong) != 0)) { fprintf(stderr, "pingpong: pthread_create failed %s\\n", strerror(errno)); exit(1); } pthread_join(ping_id1, 0); pthread_join(pong_id1, 0); pthread_join(ping_id2, 0); pthread_join(pong_id2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&ping_cv); pthread_cond_destroy(&pong_cv); printf("Main thread exiting\\n"); }
0