text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct binary_sem * bsem_init(void) { struct binary_sem *bsem; bsem = (struct binary_sem *)malloc(sizeof(struct binary_sem)); if(bsem == 0){ printf("malloc binary semaphore failed...\\n"); return 0; } pthread_mutex_init(&bsem->mutex, 0); pthread_cond_init(&bsem->cond, 0); bsem->lock = 0; return bsem; } void bsem_post(struct binary_sem *bsem) { pthread_mutex_lock(&(bsem->mutex)); bsem->lock = 1; pthread_cond_signal(&bsem->cond); pthread_mutex_unlock(&(bsem->mutex)); } void bsem_all_post(struct binary_sem *bsem) { pthread_mutex_lock(&(bsem->mutex)); bsem->lock = 1; pthread_cond_broadcast(&(bsem->cond)); pthread_mutex_unlock(&(bsem->mutex)); } void bsem_wait(struct binary_sem *bsem) { pthread_mutex_lock(&(bsem->mutex)); do{ pthread_cond_wait(&(bsem->cond), &(bsem->mutex)); }while(bsem->lock == 0); bsem->lock = 0; pthread_mutex_unlock(&(bsem->mutex)); } struct binary_sem * bsem_reset(void) { return bsem_init(); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER; pthread_cond_t not_full = PTHREAD_COND_INITIALIZER; int num_of_cooks; int num_of_phils; struct queue { int first, last; int thread_counter_id; int data[]; }; void initQ(struct queue *q); int insertQ(struct queue *q, int value); int emptyQ(struct queue *q); int removeQ(struct queue *q); int fullQ(struct queue *q, int size); void* cook(void* arg); void* eat(void* arg); void* cook(void* arg) { struct queue *q = (struct queue*) arg; usleep(1000000); pthread_mutex_lock(&mutex); while(fullQ(q,num_of_phils)) { pthread_cond_wait(&not_full,&mutex); } int meal = insertQ(q, 1234); pthread_mutex_unlock(&mutex); pthread_cond_signal(&not_empty); pthread_exit(0); } void* eat(void* arg) { struct queue *q = (struct queue*) arg; unsigned short state[3]; unsigned int seed = time(0) + (unsigned int) pthread_self(); memcpy(state, &seed, sizeof(seed)); long int random_number = nrand48(state); while(random_number > 4000000) { random_number = random_number - 1000000; } printf ("Sleep time: %li.\\n", random_number); usleep(1000000); pthread_mutex_lock(&mutex); while(emptyQ(q)) { printf("stuck in while loop\\n"); pthread_cond_wait(&not_empty, &mutex); } int meal_number = removeQ(q); printf ("Phil picked up meal number: %d, from queue spot %d.\\n", meal_number, q->first); pthread_mutex_unlock(&mutex); pthread_cond_signal(&not_full); usleep(500000); pthread_exit(0); } int main(int argc, char **argv) { if(argc < 2) { printf ("Usage: %s <num 1> <num 2> ... <num-n>\\n", argv[0]); exit(-1); } num_of_cooks = atoi(argv[1]); num_of_phils = atoi(argv[2]); struct queue *queue; queue = (struct queue*) malloc(sizeof(*queue) + (num_of_phils * sizeof(queue->data[0]))); printf ("Num of cooks: %d\\n", num_of_cooks); printf ("Num of philosophers: %d\\n", num_of_phils); initQ(queue); queue->thread_counter_id = 0; pthread_t tids_cooks[num_of_cooks]; pthread_t tids_phils[num_of_phils]; for (int i = 0; i < num_of_cooks; i++) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tids_cooks[i], &attr, cook, queue); } for (int i = 0; i < num_of_phils; i++) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tids_phils[i], &attr, eat, queue); } int total_threads = num_of_cooks + num_of_phils; for(int i = 0; i < total_threads; i++) { if(i < num_of_cooks) { pthread_join(tids_cooks[i], 0); printf("closing cook thread: %d\\n", i); } if(i < num_of_phils) { pthread_join(tids_phils[i], 0); printf("closing phil thread: %d\\n", i); } if(i >= num_of_cooks && i >= num_of_phils) i = total_threads; } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&not_full); pthread_cond_destroy(&not_empty); free(queue); } void initQ(struct queue *q) { q->first = -1; q->last = -1; pthread_cond_init(&not_full, 0); pthread_cond_init(&not_empty, 0); printf ("Queue has been initialized: firstval= %d lastval = %d.\\n", q->first, q->last); } int emptyQ(struct queue *q) { if(q->first == -1) { return(1); } else return(0); } int fullQ(struct queue *q, int size) { if(q->last == size-1) { pthread_cond_wait(&not_full, &mutex); return 1; } else return (0); } int insertQ(struct queue *q, int value) { printf("In insertQ function: qlast val is: %d.\\n", q->last); if(q->last == -1) { q->first = 0; q->last = 0; q->data[0] = value; printf("Inserted into %d space on queue\\n", q->last); return(q->data[0]); } else { q->last = q->last + 1; q->data[q->last] = value; printf("Inserted into %d space on queue\\n", q->last); return(q->data[q->last]); } } int removeQ(struct queue *q) { int value; if(q->first == q->last) { value = q->data[q->first]; printf("in removeQ qfirst is: %d\\n", q->first); q->first = -1; q->last = -1; return(value); } else { value = q->data[q->first]; printf("in removeQ qfirst is: %d\\n", q->first); q->first = q->first + 1; return(value); } }
0
#include <pthread.h> int GLOBAL = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* affiche(void* arg) { int* num = (int*) arg; int random = (int) (10*((double)rand())/ 32767); printf("THREAD %d ; Random: %d\\n", *num, random); pthread_mutex_lock(&mutex); GLOBAL+=random; pthread_mutex_unlock(&mutex); *num *= 2; pthread_exit(arg); } int main(int argc, char* argv[]) { int nb_thread; pthread_t* tids; int i; int* dup_i; if(argc != 2) { printf("Bad args\\n"); return 1; } nb_thread = atoi(argv[1]); tids = malloc(sizeof(pthread_t)*nb_thread); for(i = 0; i < nb_thread; i++) { dup_i = malloc(sizeof(int)); *dup_i = i; if(pthread_create(&tids[i], 0, affiche, dup_i) != 0) { perror("error p_create"); return 1; } } for(i = 0; i < nb_thread; i++) { if(pthread_join(tids[i], (void**) &dup_i) != 0) { perror("error p_join"); return 1; } printf("Retour mult: %d\\n", *((int*)(int*)dup_i)); } printf("GLOBAL: %d\\n", GLOBAL); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> int write_to_buffer(struct fifo_buffer* fbuf, const char* data, int data_length) { int res = 0; int from; int first_part_size; pthread_mutex_lock(&fbuf->lock); if ( fbuf->size + data_length > MAX_FIFO_BUFFER_CAPACITY ) { res = -1; goto done; } from = (fbuf->pos + fbuf->size) % MAX_FIFO_BUFFER_CAPACITY; first_part_size = ((MAX_FIFO_BUFFER_CAPACITY - from)<(data_length)) ? (MAX_FIFO_BUFFER_CAPACITY - from) : (data_length); memcpy(fbuf->buffer + from, data, first_part_size); if ( first_part_size < data_length ) { memcpy(fbuf->buffer, data + first_part_size, data_length - first_part_size); } fbuf->size += data_length; pthread_cond_broadcast(&fbuf->cond); fflush(stdout); res = data_length; done: pthread_mutex_unlock(&fbuf->lock); return res; } int read_from_buffer(struct fifo_buffer* fbuf, int requested_bytes, char* result, int* result_length) { int res = 0; int first_part_size = 0; struct timespec timeout; clock_gettime(CLOCK_REALTIME, &timeout); timeout.tv_sec += 15; if ( requested_bytes > MAX_FIFO_BUFFER_CAPACITY ) { printf("Invalid request for %d bytes\\n", requested_bytes); return -EINVAL; } res = pthread_mutex_lock(&fbuf->lock); if ( res ) { goto done; } while ( requested_bytes > fbuf->size ) { res = pthread_cond_timedwait(&fbuf->cond, &fbuf->lock, &timeout); if ( res ) { res = -res; goto done; } } first_part_size = ((MAX_FIFO_BUFFER_CAPACITY - fbuf->pos)<(requested_bytes)) ? (MAX_FIFO_BUFFER_CAPACITY - fbuf->pos) : (requested_bytes); memcpy(result, fbuf->buffer + fbuf->pos, first_part_size); if ( first_part_size < requested_bytes ) { memcpy(result + first_part_size, fbuf->buffer, requested_bytes - first_part_size); } res = *result_length = requested_bytes; fbuf->size -= requested_bytes; if ( fbuf->size == 0 ) fbuf->pos = 0; else fbuf->pos = ( fbuf->pos + requested_bytes ) % MAX_FIFO_BUFFER_CAPACITY; done: pthread_mutex_unlock(&fbuf->lock); return res; }
0
#include <pthread.h> pthread_mutex_t m[1]; pthread_cond_t c[1]; long x, y; void produce(long z) { pthread_mutex_lock(m); assert(y == z); while (x != y) { pthread_cond_wait(c, m); } y++; pthread_cond_signal(c); pthread_mutex_unlock(m); } void consume(long z) { pthread_mutex_lock(m); assert(x == z); while (x == y) { pthread_cond_wait(c, m); } assert(y == z + 1); x++; pthread_cond_signal(c); pthread_mutex_unlock(m); } long n; } arg_t; void * producer(void * arg_) { arg_t * arg = (arg_t *)arg_; long n = arg->n; long i; for (i = 0; i < n; i++) { produce(i); } return 0; } void * consumer(void * arg_) { arg_t * arg = (arg_t *)arg_; long n = arg->n; long i; for (i = 0; i < n; i++) { consume(i); } return 0; } int main(int argc, char ** argv) { long n = (argc > 1 ? atoi(argv[1]) : 10000); pthread_mutex_init(m, 0); pthread_cond_init(c, 0); x = y = 0; arg_t arg[1] = { { n } }; pthread_t cons_tid, prod_tid; pthread_create(&cons_tid, 0, consumer, arg); pthread_create(&prod_tid, 0, producer, arg); pthread_join(prod_tid, 0); pthread_join(cons_tid, 0); if (x == n && y == n) { printf("OK: n == y == z == %ld\\n", n); return 0; } else { printf("NG: n == %ld, x == %ld, y == %ld\\n", x, y, n); return 1; } }
1
#include <pthread.h> { char estado; pthread_t thread; } filosofo_t; filosofo_t * filosofos; { char estado; pthread_cond_t cond; } garfo_t; garfo_t * garfos; int numFG = 0; pthread_cond_t chairs; int numChairs = 0; pthread_mutex_t mutex; pthread_mutex_t mutexImpressao; pthread_cond_t filosofosInicializados; pthread_mutex_t mutexFilosofosInicializados; int numFilosofosInicializados; void imprimeEstado(void); void * comportamentoFilosofo(void * arg); int main (int argc, char ** argv) { int i; if (argc != 2) { fprintf(stderr, "\\nUso: ./jantar_semaforos n \\nn: numero de filosofos e garfos.\\n"); return 0; } numFG = atoi(argv[1]); if (numFG == 0) { fprintf(stderr, "\\nNumero de filosofos e garfos invalido. Uso: ./jantar_semaforos n \\nn: numero de filosofos e garfos.\\n"); return 0; } pthread_mutex_init(&mutexImpressao,0); pthread_cond_init(&filosofosInicializados, 0); pthread_mutex_init(&mutexFilosofosInicializados,0); garfos = (garfo_t *) malloc(sizeof(garfo_t) * numFG); for (i = 0; i < numFG; i++) { pthread_cond_init(&(garfos[i].cond), 0); } pthread_mutex_init(&mutex, 0); numChairs = numFG-1; pthread_cond_init(&chairs, 0); filosofos = (filosofo_t *) malloc(sizeof(filosofo_t) * numFG); numFilosofosInicializados = 0; for (i=0; i < numFG; i++) { filosofos[i].estado = 'I'; numFilosofosInicializados += 1; pthread_create(&(filosofos[i].thread), 0, comportamentoFilosofo, (void*)i); } while (1) { sleep(100); } } void * comportamentoFilosofo(void * arg) { pthread_mutex_lock(&mutexFilosofosInicializados); while(numFilosofosInicializados < numFG) pthread_cond_wait(&filosofosInicializados,&mutexFilosofosInicializados); pthread_cond_signal(&filosofosInicializados); pthread_mutex_unlock(&mutexFilosofosInicializados); int id = (int) arg; int garfoEsq, garfoDir; garfoEsq = id; garfoDir = (id + 1) % numFG; while(1) { if (filosofos[id].estado == 'I') { filosofos[id].estado = 'T'; imprimeEstado(); sleep(rand() % 10 + 1); } else if (filosofos[id].estado == 'E') { filosofos[id].estado = 'T'; imprimeEstado(); pthread_mutex_lock(&mutex); garfos[garfoEsq].estado = 'N'; pthread_cond_signal(&(garfos[garfoEsq].cond)); garfos[garfoDir].estado = 'N'; pthread_cond_signal(&(garfos[garfoDir].cond)); numChairs++; pthread_cond_signal(&chairs); pthread_mutex_unlock(&mutex); sleep(rand() % 10 + 1); } else if (filosofos[id].estado == 'T') { filosofos[id].estado = 'H'; imprimeEstado(); pthread_mutex_lock(&mutex); while(numChairs == 0) pthread_cond_wait(&chairs, &mutex); numChairs--; pthread_mutex_unlock(&mutex); if(id == 0) { pthread_mutex_lock(&mutex); while(garfos[garfoDir].estado == 'S') pthread_cond_wait(&(garfos[garfoDir].cond), &mutex); garfos[garfoDir].estado = 'S'; while(garfos[garfoEsq].estado == 'S') pthread_cond_wait(&(garfos[garfoEsq].cond), &mutex); garfos[garfoEsq].estado = 'S'; pthread_mutex_unlock(&mutex); } else { pthread_mutex_lock(&mutex); while(garfos[garfoEsq].estado == 'S') pthread_cond_wait(&(garfos[garfoEsq].cond), &mutex); garfos[garfoEsq].estado = 'S'; while(garfos[garfoDir].estado == 'S') pthread_cond_wait(&(garfos[garfoDir].cond), &mutex); garfos[garfoDir].estado = 'S'; pthread_mutex_unlock(&mutex); } } else if (filosofos[id].estado == 'H') { filosofos[id].estado = 'E'; imprimeEstado(); sleep(rand() % 10 + 1); } } } void imprimeEstado(void) { int i; pthread_mutex_lock(&mutexImpressao); for (i = 0; i < numFG; i++) fprintf(stderr, "%c ", filosofos[i].estado); fprintf(stderr, "\\n"); pthread_mutex_unlock(&mutexImpressao); }
0
#include <pthread.h> int thread_counter = 0; int * test_array; int i, length, t; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * count3s(void * arg){ int id = *((int *) arg); id--; int length_per_thread = length/t; int start = id *length_per_thread; for(i = start; i < start+length_per_thread; i++){ if(test_array[i] == 3){ pthread_mutex_lock(&mutex); thread_counter++; pthread_mutex_unlock(&mutex); } } } int main(int argc, char *argv[]) { struct timespec start, end; double cpu_time_used_iterative, cpu_time_used_threads; int i, n_threads, array_size, debug_flag; int counter_of_3 = 0; if(argc > 2){ if(argc >= 3){ array_size = atoi(argv[1]); n_threads = atoi(argv[2]); if(argc == 4){ debug_flag = 1; } else { debug_flag = 0; } } } else { fprintf(stderr, "Not enough inputs \\n"); return(1); } length = array_size; t = n_threads; test_array = (int *) malloc(sizeof(int*)*array_size); for(i = 0; i < array_size; i++){ test_array[i] = (1 + rand() % ((4)+1 - (1)) ); if(debug_flag == 1 ){ printf("test_array[%d] = %d\\n", i, test_array[i]); } } clock_gettime(CLOCK_MONOTONIC, &start); for(i = 0; i < array_size; i++){ if(test_array[i] == 3) counter_of_3++; } clock_gettime(CLOCK_MONOTONIC, &end); cpu_time_used_iterative = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec); pthread_t tids[n_threads]; clock_gettime(CLOCK_MONOTONIC, &start); for(i = 0; i < n_threads; i++){ pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tids[i], &attr, count3s, &i); } int x; for(x = 0; x < n_threads; x++){ pthread_join(tids[x], 0); } clock_gettime(CLOCK_MONOTONIC, &end); cpu_time_used_threads = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec); printf("%f\\n",cpu_time_used_threads); }
1
#include <pthread.h> struct s { int datum; struct s *next; }; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = 0; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } pthread_mutex_t mutex[10]; struct s *slot[10]; void *t_fun(void *arg) { int i; for (i=0; i<10; i++) { pthread_mutex_lock(&mutex[0]); list_add(new(10 +i), slot[i]); pthread_mutex_unlock(&mutex[0]); } return 0; } int main () { int j; struct s *p; pthread_t t1; for (j=0; j<10; j++) { pthread_mutex_init(&mutex[j],0); slot[j] = new(j); } pthread_create(&t1, 0, t_fun, 0); for (j=0; j<10; j++) { pthread_mutex_lock(&mutex[j]); list_add(new(j), slot[j]); p = slot[j]->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&mutex[j]); } return 0; }
0
#include <pthread.h> unsigned int seed; int n_epochs; long long int *in; } pi_params_t; pthread_mutex_t pi_update_lock; void pi_computer (void *t_params) { pi_params_t *params = (pi_params_t *) t_params; long long unsigned int i; double x, y, d; long long int in = 0; int n_epochs = params->n_epochs; unsigned int seed = params->seed; for (i = 0; i < n_epochs; i++) { x = (rand_r(&seed) % 1000000) / 500000.0 - 1; y = (rand_r(&seed) % 1000000) / 500000.0 - 1; d = x * x + y * y; if (d <= 1) in += 1; } pthread_mutex_lock(&pi_update_lock); *params->in += in; pthread_mutex_unlock(&pi_update_lock); } double pi (int n_epochs, int n_threads) { int i, failed; long long int result = 0; pthread_t *workers = (pthread_t *) malloc(n_threads * sizeof(pthread_t)); pi_params_t *params = (pi_params_t *)malloc(n_threads * sizeof(pi_params_t)); int n_local_epochs = n_epochs / n_threads; for (i = 0; i < n_threads; i++) { params[i].seed = rand(); params[i].n_epochs = n_local_epochs; params[i].in = &result; if (i == n_threads -1) params[i].n_epochs += n_epochs % n_threads; failed = pthread_create(&workers[i], 0, pi_computer, (void *)&params[i]); if (failed) { fprintf(stderr, "Failed to create thread (code: %d).\\n", failed); exit(1); } } for (i = 0; i < n_threads; i++) pthread_join(workers[i], 0); return 4 * result / (double) n_epochs; } int main (void) { int n_threads; unsigned int n_epochs; long unsigned int elapsed; struct timeval start, end; scanf("%d %u", &n_threads, &n_epochs); srand(time(0)); gettimeofday(&start, 0); double estimated_pi = pi(n_epochs, n_threads); gettimeofday(&end, 0); elapsed = end.tv_sec * 1000000 + end.tv_usec - start.tv_sec * 1000000 + start.tv_usec; printf("%lf\\n%lu\\n", estimated_pi, elapsed); return 0; }
1
#include <pthread.h> double x, y, z; double mass; } Particle; double xold, yold, zold; double fx, fy, fz; } ParticleV; Particle * particles; ParticleV * pv; static long seed = 123456789; double global_max_f; double dt, dt_old, dt_tmp; unsigned npart, num_threads; unsigned range; pthread_mutex_t global_mutex; double Random(void) { const long Q = 2147483647 / 48271; const long R = 2147483647 % 48271; long t; t = 48271 * (seed % Q) - R * (seed / Q); if (t > 0) seed = t; else seed = t + 2147483647; return ((double) seed / 2147483647); } static void *InitParticles(void*); static void *ComputeForces(void*); static void *ComputeNewPos(void*); static void ParallelFunc(void*); int main(int argc, char **argv) { fprintf(stdout, "\\nSIMULANDO\\n"); int i; unsigned cnt; double sim_t; if(argc != 4){ printf("Wrong number of parameters.\\nUsage: nbody num_bodies timesteps num_threads\\n"); exit(1); } npart = (unsigned)atoi(argv[1]); cnt = (unsigned)atoi(argv[2]); num_threads = (unsigned)atoi(argv[3]); dt = 0.001; dt_old = 0.001; dt_tmp = 0.0; range = npart / num_threads; particles = (Particle *) malloc(sizeof(Particle)*npart); pv = (ParticleV *) malloc(sizeof(ParticleV)*npart); if(particles == 0 || pv == 0){ fprintf(stdout, "ERROR: Failed to allocate memory to particles.\\n"); exit(1); } pthread_mutex_init(&global_mutex, 0); ParallelFunc(&InitParticles); sim_t = 0.0; while (cnt--) { ParallelFunc(&ComputeForces); ParallelFunc(&ComputeNewPos); } pthread_mutex_destroy(&global_mutex); free(particles); free(pv); return 0; } static void *InitParticles(void *tid) { unsigned begin_range = range * ((unsigned)(intptr_t)tid); unsigned end_range = begin_range + range; if (((unsigned)(intptr_t)tid) == num_threads - 1 && num_threads % 2 != 0) { end_range = npart; } int i; for (i = begin_range; i != end_range; ++i) { particles[i].x = Random(); particles[i].y = Random(); particles[i].z = Random(); particles[i].mass = 1.0; pv[i].xold = particles[i].x; pv[i].yold = particles[i].y; pv[i].zold = particles[i].z; pv[i].fx = 0; pv[i].fy = 0; pv[i].fz = 0; } } static void *ComputeForces(void *tid) { unsigned begin_range = range * ((unsigned)(intptr_t)tid); unsigned end_range = begin_range + range; if (((unsigned)(intptr_t)tid) == num_threads - 1 && num_threads % 2 != 0) { end_range = npart; } double max_f; int i; max_f = 0.0; for (i = begin_range; i != end_range; ++i) { int j; double xi, yi, mi, rx, ry, mj, r, fx, fy, rmin; rmin = 100.0; xi = particles[i].x; yi = particles[i].y; fx = 0.0; fy = 0.0; for (j = 0; j != npart; j++) { rx = xi - particles[j].x; ry = yi - particles[j].y; mj = particles[j].mass; r = rx * rx + ry * ry; if (r == 0.0) continue; if (r < rmin) rmin = r; r = r * sqrt(r); fx -= mj * rx / r; fy -= mj * ry / r; } pv[i].fx += fx; pv[i].fy += fy; fx = sqrt(fx*fx + fy*fy)/rmin; if (fx > max_f) max_f = fx; } pthread_mutex_lock(&global_mutex); if (max_f > global_max_f) global_max_f = max_f; pthread_mutex_unlock(&global_mutex); } static void *ComputeNewPos(void *tid) { unsigned begin_range = range * ((unsigned)(intptr_t)tid); unsigned end_range = begin_range + range; if (((unsigned)(intptr_t)tid) == num_threads - 1 && num_threads % 2 != 0) { end_range = npart; } int i; double a0, a1, a2; double dt_new; a0 = 2.0 / (dt * (dt + dt_old)); a2 = 2.0 / (dt_old * (dt + dt_old)); a1 = -(a0 + a2); for (i = begin_range; i != end_range; ++i) { double xi, yi; xi = particles[i].x; yi = particles[i].y; particles[i].x = (pv[i].fx - a1 * xi - a2 * pv[i].xold) / a0; particles[i].y = (pv[i].fy - a1 * yi - a2 * pv[i].yold) / a0; pv[i].xold = xi; pv[i].yold = yi; pv[i].fx = 0; pv[i].fy = 0; } dt_new = 1.0/sqrt(global_max_f); if (dt_new < 1.0e-6) dt_new = 1.0e-6; if (dt_new < dt) { dt_old = dt; dt = dt_new; } else if (dt_new > 4.0 * dt) { dt_old = dt; dt *= 2.0; } pthread_mutex_lock(&global_mutex); if (dt_old != dt_tmp) dt_tmp = dt_old; pthread_mutex_unlock(&global_mutex); } static void ParallelFunc(void* function) { pthread_t threads[num_threads]; unsigned i; for (i = 0; i != num_threads; ++i) { pthread_create(&threads[i], 0, function, (void*)(intptr_t)(i)); } for (i = 0; i != num_threads; ++i) { pthread_join(threads[i], 0); } }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; 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 == 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 lock_1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_3 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_4 = PTHREAD_MUTEX_INITIALIZER; void* thread_one(void* arg) { (void)arg; pthread_mutex_lock(&lock_1); pthread_mutex_lock(&lock_2); pthread_mutex_lock(&lock_3); pthread_mutex_lock(&lock_4); pthread_mutex_unlock(&lock_4); pthread_mutex_unlock(&lock_3); pthread_mutex_unlock(&lock_2); pthread_mutex_unlock(&lock_1); return 0; } void* thread_two(void* arg) { (void)arg; pthread_mutex_lock(&lock_1); pthread_mutex_lock(&lock_2); pthread_mutex_lock(&lock_4); pthread_mutex_lock(&lock_3); pthread_mutex_unlock(&lock_3); pthread_mutex_unlock(&lock_4); pthread_mutex_unlock(&lock_2); pthread_mutex_unlock(&lock_1); return 0; } int main() { puts("Starting T0"); pthread_t t0; int r = pthread_create(&t0, 0, thread_one, 0); if (r != 0) { err(r, "Failed to start thread: %s", strerror(r)); } puts("Joining T0"); pthread_join(t0, 0); puts("Starting T1"); pthread_t t1; r = pthread_create(&t1, 0, thread_two, 0); if (r != 0) { err(r, "Failed to start thread: %s", strerror(r)); } puts("Joining T1"); pthread_join(t1, 0); if (pthread_equal(t1, t0) != 0) { puts("For some reason t0 == t1"); return 1; } puts("Bye"); return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; unsigned long long main_counter,counter[3]={0}; void* thread_worker(void* arg) { int thread_num = *(int*)arg; free((int*)arg); for(;;) { pthread_mutex_lock(&mutex); counter[thread_num]++; main_counter++; pthread_mutex_unlock(&mutex); } } int main(int argc,char* argv[]) { int i,rtn,ch; pthread_t pthread_id[3] = {0}; int *param; for(i=0;i<3;i++) { param = (int*)malloc(sizeof(int)); *param = i; pthread_create(&pthread_id[i],0,thread_worker,param); } do { pthread_mutex_lock(&mutex); unsigned long long sum = 0; for(i=0;i<3;i++) { sum += counter[i]; printf("No.%d: %llu\\n",i,counter[i]); } printf("%llu/%llu\\n",main_counter,sum); pthread_mutex_unlock(&mutex); }while((ch = getchar())!='q'); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> int sum = 0; float max = 9.0; pthread_mutex_t mutex; void* calculer(void* arg) { int j = (int)arg; int alea = (int) (max * rand() / 32767); fprintf(stdout, "Thread %i choisit %d\\n", j, alea); pthread_mutex_lock(&mutex); sum += alea; pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char* argv[]) { int total = atoi(argv[1]); int i; int ret; pthread_t tid[total]; pthread_mutex_init(&mutex, 0); srand(time(0) + getpid()); for(i = 0 ; i < total ; i++) { ret = pthread_create(&tid[i], 0, calculer, (void*)i); if(ret != 0) { fprintf(stdout, "Can't create thread !\\n"); exit(1); } } for(i = 0 ; i < total ; i++) { ret = pthread_join(tid[i], 0); if(ret != 0) { fprintf(stdout, "Thread is not joinable !\\n"); exit(1); } } fprintf(stdout, "THREAD : Somme totale = %d\\n", sum); pthread_mutex_destroy(&mutex); exit(0); }
0
#include <pthread.h> volatile int progress; void nsleep (long nsec) { struct timespec sleepTime, remainingSleepTime; sleepTime.tv_sec = 0; sleepTime.tv_nsec = nsec; while (nanosleep(&sleepTime, &remainingSleepTime) != 0) sleepTime = remainingSleepTime; } void *monitor (void *p) { while (1) { progress = 0; nsleep(100000000); if (!progress) { fprintf(stderr, "deadlock!"); exit(1); } } } struct group { int fst; int snd; pthread_mutex_t * a; pthread_mutex_t * b; int v; }; void *functionA(); void *functionB(); pthread_mutexattr_t mutexAttribute; int main() { int rc1, rc2; pthread_t thread1, thread2,m; printf("Program started\\n"); struct group * g ; g = (struct group *) malloc(sizeof(struct group)); g->a = (pthread_mutex_t * ) malloc(sizeof(pthread_mutex_t)); g->b = (pthread_mutex_t * ) malloc(sizeof(pthread_mutex_t)); g->v = 5; int * a; a = (int * ) malloc(sizeof(int)); int status = pthread_mutexattr_init (&mutexAttribute); if (status != 0) { } status = pthread_mutexattr_settype(&mutexAttribute, PTHREAD_MUTEX_RECURSIVE_NP); if (status != 0) { } status = pthread_mutex_init(g->a, &mutexAttribute); if (status != 0) { } status = pthread_mutex_init(g->b, &mutexAttribute); if (status != 0) { } if( (rc1=pthread_create( &thread1, 0, &functionA, g)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionB, g)) ) { printf("Thread creation failed: %d\\n", rc2); } usleep(50); pthread_create(&m, 0, monitor, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); return 0; } void *functionA(struct group * g) { progress = 1; pthread_mutex_t * g1; pthread_mutex_t * g2; g1 = g->a; g2 = g->b; int i = 0; struct group * h; h = g; for (i = 0; i < 10000; i++){ if (g->v % 2 == 0) { progress = 1; if(i%100 == 0) fprintf(stderr,"\\nTHREAD A: %d",i); pthread_mutex_lock( g1 ); pthread_mutex_lock( g2 ); pthread_mutex_lock( g2 ); g->v ++; usleep(10); pthread_mutex_unlock( g2 ); pthread_mutex_unlock( g2 ); pthread_mutex_unlock( g1 ); } else { pthread_mutex_lock( h->b ); pthread_mutex_lock( h->a ); g->v ++; pthread_mutex_unlock( h->a ); pthread_mutex_unlock( h->b ); } } g->v ++; return (void *) 0; } void *functionB(struct group * g) { progress = 1; int i ; for (i = 0; i < 10000; i++){ progress = 1; if (g->v % 2 == 0) { if(i%100 == 0) fprintf(stderr,"\\nTHREAD B: %d",i); pthread_mutex_lock( g->a ); pthread_mutex_lock( g->b ); g->v ++; usleep(10); pthread_mutex_unlock( g->b ); pthread_mutex_unlock( g->a ); } else { pthread_mutex_lock( g->b ); pthread_mutex_lock( g->a ); g->v ++; pthread_mutex_unlock( g->a ); pthread_mutex_unlock( g->b ); } } return (void *) 0; }
1
#include <pthread.h> pthread_t tid[2]; int counter; pthread_mutex_t lock; void* doSomeThing(void *arg) { pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf("\\n Job %d started\\n", counter); for(i=0; i<(100000000);i++); printf("\\n Job %d finished\\n", counter); pthread_mutex_unlock(&lock); return 0; } int main(void) { int i = 0; int err; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } while(i < 2) { err = pthread_create(&(tid[i]), 0, doSomeThing, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); i++; } pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> int read_cnt = 0, write_cnt = 0; int write_flag = 1; pthread_mutex_t read_m, write_m, access_m; int cnt = 4; void *write_handler(void * arg); void *read_handler(void* arg); int main() { pthread_t read_tid, write_tid; srand(getpid()); pthread_mutex_init(&read_m, 0); pthread_mutex_init(&write_m, 0); pthread_mutex_init(&access_m, 0); while(1) { if(rand()%2 == 0) { pthread_create(&read_tid, 0, write_handler, 0); } else { pthread_create(&write_tid, 0, read_handler, 0); } sleep(1); } pthread_mutex_destroy(&read_m); pthread_mutex_destroy(&write_m); pthread_mutex_destroy(&access_m); return 0; } void* read_handler(void * arg) { pthread_detach(pthread_self()); while(write_cnt > 0) { } pthread_mutex_lock(&read_m); if(read_cnt == 0) pthread_mutex_lock(&access_m); read_cnt++; pthread_mutex_unlock(&read_m); printf("read cnt: %d\\n", cnt); sleep(1); pthread_mutex_lock(&read_m); read_cnt--; if(read_cnt == 0) pthread_mutex_unlock(&access_m); pthread_mutex_unlock(&read_m); } void *write_handler(void* arg) { pthread_detach(pthread_self()); pthread_mutex_lock(&write_m); write_cnt++; pthread_mutex_unlock(&write_m); pthread_mutex_lock(&access_m); sleep(1); printf("before write cnt:%d\\n", cnt); cnt++; printf("after write cnt:%d\\n", cnt); pthread_mutex_unlock(&access_m); pthread_mutex_lock(&write_m); write_cnt--; pthread_mutex_unlock(&write_m); }
1
#include <pthread.h> pthread_mutex_t garfo[5]; int state[5], pratadas; void* filosofo(void *arg) { int i; i=*((int*)arg); while(1) { printf("Filosofo %d pensando!!!\\n",i); sleep(rand()%3); if(state[i+1]==0 && state[(i+(5 -1))%5]==0) { state[i]=1; pthread_mutex_lock(&garfo[i]); pthread_mutex_lock(&garfo[(i+(5 -1))%5]); printf("Filosofo %d comendo com garfos %d e %d!!!\\n",i,i,(i+(5 -1))%5); pratadas++; printf("Ja foram %d pratadas de macarrão.\\n\\n",pratadas); sleep(rand()%3); pthread_mutex_unlock(&garfo[i]); pthread_mutex_unlock(&garfo[(i+(5 -1))%5]); state[i]=0; } } pthread_exit(0); } int main(int argc, char **argv) { pthread_t filosofos[5]; int codigo_de_erro, i, id[5]; pratadas=0; for(i=0;i<5;i++) { pthread_mutex_init(&garfo[i], 0); id[i]=i; state[i]=0; } for(i=0;i<5;i++) { codigo_de_erro = pthread_create(&filosofos[i], 0, filosofo, (void*)&id[i]); if(codigo_de_erro != 0) { printf("Erro na criação de thread filha, Codigo de erro %d\\n", codigo_de_erro); exit(1); } } for(i=0;i<5;i++) { pthread_join(filosofos[i], 0); } return 0; }
0
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mutex; pthread_cond_t threshold; int number = 0, i = 0; void *threadlock(int thread_num) { pthread_mutex_lock(&mutex); if (thread_num == 2 && number == 0){ pthread_cond_wait(&threshold, &mutex); } pthread_mutex_unlock(&mutex); for (i = 0; i < 10; i++){ pthread_mutex_lock(&mutex); if (thread_num == 1) printf("thread 1 : "); else if (thread_num == 2) printf("thread 2 : "); printf("number = %d, i = %d\\n", number, i); number++; pthread_cond_signal(&threshold); if (i == 9){ pthread_mutex_unlock(&mutex); break; } pthread_cond_wait(&threshold, &mutex); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void thread_create(void) { pthread_mutex_lock(&mutex); if ((pthread_create(&thread[1], 0, threadlock, 2)) != 0) printf("create function : thread 2 create fail\\n"); else printf("create function : Thread 2 is established\\n"); if ((pthread_create(&thread[0], 0, threadlock, 1)) != 0) printf("create function : thread 1 create fail\\n"); else printf("create function : Thread 1 is established\\n"); pthread_mutex_unlock(&mutex); } void thread_wait(void) { if (thread[0] != 0){ pthread_join(thread[0], 0); printf("wait function : Thread 1 over\\n"); } if (thread[1] != 0){ pthread_join(thread[1], 0); printf("wait function : Thread 2 over\\n"); } } int main() { pthread_mutex_init(&mutex,0); printf("main funtion : establishing threads\\n"); thread_create(); printf("main funtion : waiting for threads\\n"); thread_wait(); printf("main funtion : turn me and exit\\n"); return 0; }
1
#include <pthread.h> static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER; static bool last_round; static int ntogo; static bool alldone; static void * cons (void *arg) { pthread_mutex_lock (&mut1); do { if (atomic_decrement_and_test (&ntogo)) { pthread_mutex_lock (&mut2); alldone = 1; pthread_cond_signal (&cond2); pthread_mutex_unlock (&mut2); } pthread_cond_wait (&cond1, &mut1); } while (! last_round); pthread_mutex_unlock (&mut1); return 0; } int main (int argc, char *argv[]) { int opt; int err; int nthreads = 10; int nrounds = 100; bool keeplock = 0; while ((opt = getopt (argc, argv, "n:r:k")) != -1) switch (opt) { case 'n': nthreads = atol (optarg); break; case 'r': nrounds = atol (optarg); break; case 'k': keeplock = 1; break; } ntogo = nthreads; pthread_t th[nthreads]; int i; for (i = 0; __builtin_expect (i < nthreads, 1); ++i) if (__builtin_expect ((err = pthread_create (&th[i], 0, cons, (void *) (long) i)) != 0, 0)) printf ("pthread_create: %s\\n", strerror (err)); for (i = 0; __builtin_expect (i < nrounds, 1); ++i) { pthread_mutex_lock (&mut2); while (! alldone) pthread_cond_wait (&cond2, &mut2); pthread_mutex_unlock (&mut2); pthread_mutex_lock (&mut1); if (! keeplock) pthread_mutex_unlock (&mut1); ntogo = nthreads; alldone = 0; if (i + 1 >= nrounds) last_round = 1; pthread_cond_broadcast (&cond1); if (keeplock) pthread_mutex_unlock (&mut1); } for (i = 0; i < nthreads; ++i) if ((err = pthread_join (th[i], 0)) != 0) printf ("pthread_create: %s\\n", strerror (err)); return 0; }
0
#include <pthread.h> int motorSteps; const int stepMotorDelay = 800; const int fasMotorDelay = 800; const int delayInThread = 2000; const int maxSteps = 4000; void motor_steps(int steps, int direction) { int i; if(direction == MOTOR_STEP_FORWARD) { DEBUG0("MOTOR_STEP_FORWARD"); if(steps <= maxSteps) { for(i = 0; i < steps; i++) { motor_forward_one_step(); udelay(stepMotorDelay); } } else { motor_forward_one_step(); udelay(stepMotorDelay); } } else { DEBUG0("MOTOR_STEP_BACKWARD"); if(steps <= maxSteps) { for(i = 0; i < steps; i++) { motor_backward_one_step(); udelay(stepMotorDelay); } } else { motor_backward_one_step(); udelay(stepMotorDelay); } } motor_stop(); } void* motor_autoforward_thread(void* para) { int i, error; int currentTask; struct response resp; pthread_detach(pthread_self()); bzero(&resp, sizeof(struct response)); resp.cmd = MOTOR_AUTO_FORWARD; resp.para1 = 0; resp.para2 = 0; send(connect_socket_fd, (char*)&resp, 12, 0); DEBUG0("motor auto forward"); g_DA_z = 10000; write_DA( DA_Z, g_DA_z); while(1) { pthread_mutex_lock(&g_current_task_mutex); currentTask = g_current_task; pthread_mutex_unlock(&g_current_task_mutex); if(currentTask == STOP) { goto GETOUT; } motor_forward_one_step(); usleep(delayInThread); error = getError(100); if(error < 0) break; } pid_func(); motor_stop(); resp.para1 = 0; resp.para2 = 1; send(connect_socket_fd, (char*)&resp, 12, 0); GETOUT: motor_stop(); pthread_mutex_lock(&g_current_task_mutex); g_current_task = STOP; pthread_mutex_unlock(&g_current_task_mutex); DEBUG0("motor auto forward stoped"); return (void*)0; } void* motor_autobackward_thread(void* para) { int currentTask, i; short steps = *((short*)para); struct response resp; bzero(&resp, sizeof(struct response)); resp.cmd = MOTOR_AUTO_BACKWARD; pthread_detach(pthread_self()); if(steps < 0 && steps > 4000) { steps = 800; } DEBUG1("motor auto backward %d steps..", (int)steps); for(i = 0; i < steps; i++) { pthread_mutex_lock(&g_current_task_mutex); currentTask = g_current_task; pthread_mutex_unlock(&g_current_task_mutex); if(currentTask == STOP) break; motor_backward_one_step(); usleep(delayInThread); } motor_stop(); send(connect_socket_fd, (char*)&resp, 12, 0); DEBUG0("motor auto backward stoped"); pthread_mutex_lock(&g_current_task_mutex); g_current_task = STOP; pthread_mutex_unlock(&g_current_task_mutex); return (void*)0; } void* motor_fast_forward_thread(void* para) { int currentTask; pthread_detach(pthread_self()); DEBUG0("motor fast forward.."); while(1) { pthread_mutex_lock(&g_current_task_mutex); currentTask = g_current_task; pthread_mutex_unlock(&g_current_task_mutex); if(currentTask == STOP) break; motor_forward_one_step(); usleep(delayInThread); } motor_stop(); pthread_mutex_unlock(&g_current_task_mutex); g_current_task = STOP; pthread_mutex_unlock(&g_current_task_mutex); DEBUG0("motor fast forward stoped"); return (void*)0; } void* motor_fast_backward_thread(void* para) { int currentTask; pthread_detach(pthread_self()); DEBUG0("motor fast backward.."); while(1) { pthread_mutex_lock(&g_current_task_mutex); currentTask = g_current_task; pthread_mutex_unlock(&g_current_task_mutex); if(currentTask == STOP) break; motor_backward_one_step(); usleep(delayInThread); } motor_stop(); pthread_mutex_unlock(&g_current_task_mutex); g_current_task = STOP; pthread_mutex_unlock(&g_current_task_mutex); DEBUG0("motor fast backward stoped"); return (void*)0; }
1
#include <pthread.h> struct queueNode { int key; struct queueNode *next; }; struct queueHeader { struct queueNode *head; struct queueNode *tail; pthread_mutex_t h_lock; pthread_mutex_t t_lock; }; void *hwthread(void *arg); void enqueue(struct queueHeader *qh, int key); int* dequeue(struct queueHeader *qh); int isEmpty(struct queueHeader *qh); struct queueHeader Qheader = {0,}; int main(int argc, char* argv[]) { struct timeval te; long long milliseconds; int thread_size = atoi(argv[1]), i = 0; pthread_t *p = (pthread_t *) malloc (sizeof(pthread_t) * thread_size); struct queueNode *startNode = (struct queueNode *)malloc(sizeof(struct queueNode)); gettimeofday(&te, 0); milliseconds = clock(); printf("%lld start\\n", milliseconds); startNode->key = -897; startNode->next = 0; Qheader.head = startNode; Qheader.tail = startNode; for(i = 0; i < thread_size; i++) pthread_create(&p[i], 0, hwthread, 0); for(i = 0; i < thread_size; i++) pthread_join(p[i], 0); if(!isEmpty(&Qheader)) printf(" Q isn't empty\\n"); gettimeofday(&te, 0); milliseconds = clock(); printf("%lld end\\n", milliseconds); return 0; } void *hwthread(void *arg) { int i = 0; int *key = 0; for (i = 0; i<1000000;i++){ enqueue(&Qheader, i); key = dequeue(&Qheader); if (key) free(key); else printf("queue empty\\n"); } } void enqueue(struct queueHeader *qh, int key) { struct queueNode *newNode = (struct queueNode *)malloc(sizeof(struct queueNode)); newNode->key = key; newNode->next = 0; pthread_mutex_lock(&qh->t_lock); qh->tail->next = newNode; qh->tail = newNode; pthread_mutex_unlock(&qh->t_lock); } int* dequeue(struct queueHeader *qh) { struct queueNode *delNode = 0, *preheadNode = 0; pthread_mutex_lock(&qh->h_lock); preheadNode = qh->head; if (qh->head->next) { int *retval = (int *)malloc(sizeof(int)); delNode = qh->head->next; *retval = delNode->key; qh->head->next = delNode->next; qh->head = delNode; preheadNode->key = -132; preheadNode->next = 0; free(preheadNode); pthread_mutex_unlock(&qh->h_lock); return retval; } else { pthread_mutex_unlock(&qh->h_lock); return 0; } } int isEmpty(struct queueHeader *qh) { if (!qh->head->next && !qh->tail->next) return 1; else return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int gnum = 1; void* thread1(void* arg) { for(;;) { printf("\\nin thread 1\\n"); pthread_mutex_lock(&mutex); sleep(1); while(gnum < 5) { printf("thread1:I'm blocking,waiting for gum >= 5\\n\\n"); pthread_cond_wait(&cond,&mutex); printf("thread2:I'm wake up\\n\\n"); } gnum ++; printf("thead1 add one to gnum,now gnum=%d\\n",gnum); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); return arg; } void* thread2(void* arg) { for(;;) { printf("\\nin thread 2\\n"); pthread_mutex_lock(&mutex); sleep(1); gnum ++; printf("thead2 add one to gnum,now gnum=%d\\n",gnum); if(gnum == 5) pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); return arg; } int main() { pthread_t th1; pthread_t th2; pthread_create(&th1, 0, thread1, 0); pthread_create(&th2, 0, thread2, 0); pthread_join(th1,0); printf("thread 1 exit\\n"); pthread_join(th2,0); printf("thread 2 exit\\n"); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> void *filosofo (void *id); void pegaGarfo (int, int, char *); void devolveGarfo (int, int, char *); void pensar(int); void comer(int); int comidaNaMesa (); int numero_filosofos; pthread_mutex_t *garfo; pthread_t *filo; pthread_mutex_t comidaBloqueada; int sleep_seconds = 0; int tempoComendo; int tempoPensando; int filosofoAleatorio; int main (int argn, char **argv) { int i; printf("Informe o numero de filosofos:\\n"); scanf("%d", &numero_filosofos); filosofoAleatorio = rand() % numero_filosofos; garfo = (pthread_mutex_t *) malloc(numero_filosofos*sizeof(pthread_mutex_t)); filo = (pthread_t *) malloc(numero_filosofos*sizeof(pthread_t)); printf("Informe o tempo gasto do filosofo pensando (ms):\\n"); scanf("%d", &tempoPensando); printf("Informe o tempo gasto do filosofo comendo (ms):\\n"); scanf("%d", &tempoComendo); printf("---------------------------------------------:\\n"); if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&comidaBloqueada, 0); for (i = 0; i < numero_filosofos; i++) pthread_mutex_init (&garfo[i], 0); for (i = 0; i < numero_filosofos; i++) pthread_create (&filo[i], 0, filosofo, (void *)i); for (i = 0; i < numero_filosofos; i++) pthread_join (filo[i], 0); return 0; } void *filosofo (void *num) { int id; int i, garfoEsquerdo, garfoDireito, f; id = (int)num; garfoDireito = id; garfoEsquerdo = id + 1; pensar(id); if (garfoEsquerdo == numero_filosofos) garfoEsquerdo = 0; while (f = comidaNaMesa()) { if (filosofoAleatorio == id) pegaGarfo (id, garfoEsquerdo, "esquerda"); else pegaGarfo (id, garfoDireito, "direita "); devolveGarfo(id, garfoDireito, "direita"); pegaGarfo (id, garfoDireito, "direita"); if (filosofoAleatorio != id) { devolveGarfo(id, garfoDireito, "direita"); pegaGarfo(id, garfoEsquerdo, "esquerda"); } else { comer(id); devolveGarfo(id, garfoDireito, "direita"); devolveGarfo(id, garfoEsquerdo, "esquerda"); filosofoAleatorio = rand() % numero_filosofos; pensar(id); } pegaGarfo(id, garfoDireito, "direita"); comer(id); devolveGarfo(id, garfoDireito, "direita"); devolveGarfo(id, garfoEsquerdo, "esquerda"); pensar(id); } printf ("Filosofo %d acabou de comer.\\n", id); return (0); } int comidaNaMesa () { static int comida = 25; int meuPrato; pthread_mutex_lock (&comidaBloqueada); if (comida > 0) { comida--; } meuPrato = comida; pthread_mutex_unlock (&comidaBloqueada); return comida; } void pegaGarfo (int filo, int g, char *lado) { pthread_mutex_lock (&garfo[g]); printf ("Filosfo %d FAMINTO: pega o garfo %d da %s\\n", filo, g, lado); } void devolveGarfo (int filo, int g, char *lado) { pthread_mutex_unlock(&garfo[g]); printf("Filosfo %d devolve o garfo %d da %s\\n", filo, g, lado); } void pensar(int id) { printf("Filosofo %d esta PENSANDO\\n",id); usleep(tempoPensando*1000); } void comer(int id) { printf ("Filosfo %d: COMENDO.\\n", id); usleep(tempoComendo*1000); }
0
#include <pthread.h> double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg){ int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++){ mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } void main (){ long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for(i=0; i<100000*4; i++){ a[i]=1; b[i]=a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++){ pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> int mThread=0; int start_main=0; pthread_mutex_t mStartLock; int __COUNT__ =0; void __VERIFIER_atomic_acquire() { pthread_mutex_lock(&mStartLock); } void __VERIFIER_atomic_release() { pthread_mutex_unlock(&mStartLock); } void __VERIFIER_atomic_thr1(int PR_CreateThread__RES) { if( __COUNT__ == 0 ) { mThread = PR_CreateThread__RES; __COUNT__ = __COUNT__ + 1; } else { assert(0); } } void* thr1(void* arg) { int PR_CreateThread__RES = 1; __VERIFIER_atomic_acquire(); start_main=1; __VERIFIER_atomic_thr1(PR_CreateThread__RES); __VERIFIER_atomic_release(); return 0; } void __VERIFIER_atomic_thr2(int self) { if( __COUNT__ == 1 ) { __COUNT__ = __COUNT__ + 1; } else { assert(0); } } void* thr2(void* arg) { int self = mThread; while (start_main==0); __VERIFIER_atomic_acquire(); __VERIFIER_atomic_release(); __VERIFIER_atomic_thr2(self); return 0; } int main() { pthread_t t; pthread_create(&t, 0, thr1, 0); thr2(0); return 0; }
0
#include <pthread.h> void mux_2_iord(void *not_used){ pthread_barrier_wait(&threads_creation); while(1){ pthread_mutex_lock(&control_sign); if(!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } if((( (separa_IorD & cs.value) >> IorD_POS) & 0x01) == 0){ mux_iord_buffer.value = pc; } else mux_iord_buffer.value = aluout; pthread_mutex_lock(&mux_iord_result); mux_iord_buffer.isUpdated = 1; pthread_cond_signal(&mux_iord_execution_wait); pthread_mutex_unlock(&mux_iord_result); pthread_barrier_wait(&current_cycle); mux_iord_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> pthread_t maleTID, femaleTID, makethreadTID1,makethreadTID2, makethreadTID3; sem_t male_count, female_count, empty; pthread_mutex_t mutex_male = PTHREAD_MUTEX_INITIALIZER, mutex_female = PTHREAD_MUTEX_INITIALIZER, mutex_thread=PTHREAD_MUTEX_INITIALIZER; int mcount, fcount, mtime, ftime, muse, fuse; unsigned int delay_time(unsigned int delaytime, unsigned int stddeviation); void* makethread(void*); void* male_routine(void* unused); void* female_routine(void* unused); int freq(); int main(void) { int i=0; sem_init(&male_count, 0, 5); sem_init(&female_count, 0, 5); sem_init(&empty, 0, 1); pthread_create(&makethreadTID1, 0, &makethread, 0); pthread_create(&makethreadTID2, 0, &makethread, 0); pthread_create(&makethreadTID3, 0, &makethread, 0); sleep(10); printf("\\n\\n+-------------------------------+"); printf("\\n+ %5d | %5d +",mtime, ftime); printf("\\n+ MAN | WOMAN +"); printf("\\n+-------------------------------+\\n\\n"); return 0; } void* makethread(void* unused) { int n; static int i=0; while (i < 100) { delay_time(0, 500); n=freq(); if (n == 0) pthread_create(&maleTID, 0, &male_routine, 0); else pthread_create(&femaleTID, 0, &female_routine, 0); pthread_mutex_lock(&mutex_thread); i++; pthread_mutex_unlock(&mutex_thread); } return 0; } void* male_routine(void* unused) { pthread_mutex_lock(&mutex_male); mcount++; if (mcount ==1) sem_wait(&empty); pthread_mutex_unlock(&mutex_male); sem_wait(&male_count); printf("\\n---> Man entered"); delay_time(10, 100); printf("\\nMan exited --->"); sem_post(&male_count); pthread_mutex_lock(&mutex_male); mcount--; if (mcount == 0) { printf("\\n\\n\\"Bathroom empty!\\"\\n"); printf("Man used time: %d\\n",muse+1); muse=0; sem_post(&empty); } else muse++; mtime++; pthread_mutex_unlock(&mutex_male); return 0; } void* female_routine(void* unused) { pthread_mutex_lock(&mutex_female); fcount++; if (fcount == 1) sem_wait(&empty); pthread_mutex_unlock(&mutex_female); sem_wait(&female_count); printf("\\n---> Woman entered"); delay_time(10, 100); printf("\\nWoman exited --->"); sem_post(&female_count); pthread_mutex_lock(&mutex_female); fcount --; if (fcount ==0) { printf("\\n\\n\\"Bathroom empty!\\"\\n"); printf("Woman used time: %d\\n",fuse+1); fuse=0; sem_post(&empty); } else fuse++; ftime++; pthread_mutex_unlock(&mutex_female); return 0; } int freq() { int n; srand(time(0)); n = rand() % 100; if (n<50) return 1; return 0; } unsigned int delay_time(unsigned int delaytime, unsigned int stddeviation) { unsigned int n; if (stddeviation == 0) stddeviation = 300; srand(time(0)); n = delaytime * 1000 + rand() % (stddeviation*1000); usleep(n); return n; }
0
#include <pthread.h> static int tcp_listen(char *ip, char *port); struct thread_pool { pthread_mutex_t mutex; pthread_cond_t cond; pthread_cond_t main_cond; pthread_t tids[4]; int connfd; int ready; void (*process)(int s); }; static int thread_pool_create(struct thread_pool **pool, int nthreads, void (*process)(int s)); static void thread_main(struct thread_pool *pool, int s); static void *thread_worker(void *arg); static void usage(void) { fprintf( stderr, "Usage: \\r\\n" "-p <port> <must exist>\\r\\n" "-i <ip> \\r\\n" "-n <number of threads:default %d>\\r\\n" "-h help \\r\\n" ,4 ); } void process_msg(int s) { printf("s = %d\\n", s); close(s); } static int tcp_listen(char *ip, char *port) { struct sockaddr_in server; int r, s; s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) { perror("socket"); return -1; } if (!port) { fprintf(stderr, "port is null\\n"); return -1; } memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(atoi(port)); server.sin_addr.s_addr = ip ? inet_addr(ip) : htonl(INADDR_ANY); int on = 1; if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) { perror("setsockopt"); return -1; } r = bind(s, (struct sockaddr*)&server, sizeof(server)); if (r == -1) { perror("bind"); return -1; } r = listen(s, 10); if (r == -1) { perror("listen"); return -1; } return s; } static int thread_pool_create(struct thread_pool **pool, int nthreads, void (*process)(int s)) { int i, r; struct thread_pool *p = 0; p = calloc(1, sizeof(struct thread_pool)); if (!p) goto failed0; if ((r = pthread_mutex_init(&p->mutex, 0)) != 0) goto failed; if ((r = pthread_cond_init(&p->cond, 0)) != 0) goto failed; if ((r = pthread_cond_init(&p->main_cond, 0)) != 0) goto failed; if (nthreads <= 0) nthreads = 4; for (i = 0; i < nthreads; i++) { r = pthread_create(&p->tids[i], 0, thread_worker, p); } p->process = process; *pool = p; return 0; failed: pthread_mutex_destroy(&p->mutex); pthread_cond_destroy(&p->cond); free(p); failed0: fprintf(stderr, "error:%s:%s\\n", strerror(r), strerror(errno)); return -1; } static void *thread_worker(void *arg) { struct thread_pool *p = (struct thread_pool *)arg; int connfd = -1; for (;;) { pthread_mutex_lock(&p->mutex); while (p->ready == 0) { pthread_cond_wait(&p->cond, &p->mutex); } connfd = p->connfd; p->ready = 0; pthread_cond_signal(&p->main_cond); pthread_mutex_unlock(&p->mutex); p->process(connfd); } return (void *)0; } static void thread_main(struct thread_pool *pool, int s) { int connfd; for (;;) { connfd = accept(s, 0, 0); fprintf(stderr, "current sock = %d\\n", connfd); if (connfd == -1) { perror("accept"); break; } pthread_mutex_lock(&pool->mutex); while (pool->ready == 1) { pthread_cond_wait(&pool->main_cond, &pool->mutex); } pool->connfd = connfd; pool->ready = 1; pthread_cond_signal(&pool->cond); pthread_mutex_unlock(&pool->mutex); } }
1
#include <pthread.h> void error(char *msg) { fprintf(stderr, "%s: %s\\n", msg, strerror(errno)); exit(1); } int beers = 2000000; pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; void *drink_lots(void *a) { int i; pthread_mutex_lock(&beers_lock); for (i = 0; i < 100000; i++) { beers = beers - 1; } pthread_mutex_unlock(&beers_lock); printf("beers = %i\\n", beers); return 0; } int main() { pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers); for (t = 0; t < 20; t++) { if (pthread_create(&threads[t], 0, drink_lots, 0) == -1) error("Can't create thread"); } void *result; for (t = 0; t < 20; t++) { if (pthread_join(threads[t], &result) == -1) error("Can't join threads"); } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
0
#include <pthread.h> int NUM_THREADS; long int chunk_end; long int chunk_init; pthread_mutex_t lock_x; void swapM(long int* a, long int* b) { long int aux; aux = *a; *a = *b; *b = aux; } long int divideM(long int *vec, int left, int right) { int i, j; i = left; for (j = left + 1; j <= right; ++j) { if (vec[j] < vec[left]) { ++i; pthread_mutex_lock(&lock_x); swapM(&vec[i], &vec[j]); pthread_mutex_unlock(&lock_x); } } pthread_mutex_lock(&lock_x); swapM(&vec[left], &vec[i]); pthread_mutex_unlock(&lock_x); return i; } void quickSortM(long int *vec, int left, int right) { int r; if (right > left) { r = divideM(vec, left, right); quickSortM(vec, left, r - 1); quickSortM(vec, r + 1, right); } } void *th_qs(void *vect) { long int *vec = (long int *) vect; quickSortM(vec,chunk_init, chunk_end); pthread_exit(0); } int run_t(char **fname) { int i; long int num,size=0; FILE *ptr_myfile; pthread_t tid[NUM_THREADS]; void *status; ptr_myfile=fopen(*fname,"rb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } while(fread(&num,sizeof(long int),1,ptr_myfile)) size++; size--; long int arr[size]; fseek(ptr_myfile, sizeof(long int), 0 ); for(i=0;i<size;i++) fread(&arr[i],sizeof(long int),1,ptr_myfile); fclose(ptr_myfile); pthread_mutex_init(&lock_x, 0); for ( i = 1; i < NUM_THREADS; i++) { chunk_init = chunk_end; chunk_end = (size/NUM_THREADS)*i; pthread_create(&tid[i], 0, &th_qs, (void*)arr); } for ( i = 1; i < NUM_THREADS; i++) pthread_join(tid[i], &status); chunk_init=0; chunk_end = size; pthread_create(&tid[NUM_THREADS], 0, &th_qs, (void*)arr); pthread_join(tid[NUM_THREADS], &status); return 0; } int run_p(char **fname){ int i,wpid,status; long int num,size=0; FILE *ptr_myfile; ptr_myfile=fopen(*fname,"rb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } while(fread(&num,sizeof(long int),1,ptr_myfile)) size++; size--; long int arr[size]; fseek(ptr_myfile, sizeof(long int), 0 ); for(i=0;i<size;i++) fread(&arr[i],sizeof(long int),1,ptr_myfile); fclose(ptr_myfile); for ( i = 1; i < NUM_THREADS; i++) { chunk_init = chunk_end; chunk_end = (size/NUM_THREADS)*i; if ( i==2 || i== 4 || i==6) if(fork() == 0) wpid = getpid(); quickSortM(arr,chunk_init, chunk_end); wait(&status); } quickSortM(arr,0, size); } void help(){ printf("\\nUsage: fqs [OPTION]... [FILE]...\\nSort with quicksort algoritm a file with random long ints, OPTION and FILE are mandatory, OPTION must be [-s/-m], a default run displays this help and exit.\\n\\t-t run with thread support\\n\\t-p run without multiprocess support\\n\\t\\t-h display this help and exit\\n\\t\\t-v output version information and exit\\n\\n"); } void vers(){ printf("\\nqs 1.30\\nCopyright (C) 2015 Free Software Foundation, Inc.\\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\\nThis is free software: you are free to change and redistribute it.\\nThere is NO WARRANTY, to the extent permitted by law.\\n\\nWritten by Gonçalo Faria, Luis Franco, and Vitor Filipe \\n\\n"); } int main (int argc, char *argv[]) { int rtn,total,opt; switch(argc){ case 2: opt = getopt(argc, argv, "v"); if(opt == 'v') { vers(); rtn=0; } else { help(); rtn=1; } break; case 4: NUM_THREADS=atoi(argv[3]); opt = getopt(argc, argv, "t:p:"); if(opt == 'p') rtn=run_p(&argv[2]); else if (opt == 't') rtn=run_t(&argv[2]); else { help(); rtn=1; } break; default: help(); rtn=1; break; } return rtn; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t coz, can; int comidinha = 0; void* cozinheiro() { while(1) { pthread_mutex_lock(&lock); while(comidinha != 0) { pthread_cond_wait(&coz, &lock); } printf("Comidinha restante: %d\\n", comidinha); printf("Fazendo a comidinha\\n"); sleep(1); comidinha = 20; printf("Comidinha agora: %d\\n", comidinha); sleep(1); pthread_cond_broadcast(&can); pthread_mutex_unlock(&lock); } } void* canibal() { while(1) { pthread_mutex_lock(&lock); while (comidinha == 0) { pthread_cond_wait(&can, &lock); } comidinha--; printf("Comendo comidinha!!!\\n"); if (comidinha == 0) { pthread_cond_signal(&coz); } pthread_mutex_unlock(&lock); } } int main() { pthread_t cani[5]; pthread_t cozi; pthread_create(&cozi, 0, cozinheiro, 0); for (int i = 0; i < 5; i++) { pthread_create(&cani[i], 0, canibal, 0); } pthread_join(cozi, 0); for (int i = 0; i < 5; i++) { pthread_join(cani[i], 0); } return 0; }
0
#include <pthread.h> int A[1000000]; int A_flag[1000000]; int n; int num_thrd; pthread_mutex_t k_threshold_mutex; pthread_cond_t k_threshold_cv; int Loaddata (int* A, int n) { FILE* ip; int i,j,temp; if ((ip=fopen("data_input","r"))==0) { printf("Error opening the input data.\\n"); return 1; } fscanf(ip,"%d\\n\\n",&temp); if (temp!=n) { printf("City count does not match the data!\\n"); return 2; } for (i=0;i<n;i++) for (j=0;j<n;j++) fscanf(ip,"%d\\t",A+n*i+j); fclose(ip); return 0; } int Savedata(int* A, int n) { FILE* op; int i,j,temp; if ((op=fopen("data_output","w"))==0) { printf("Error opening the file.\\n"); return 1; } fprintf(op,"%d\\n\\n",n); for (i=0;i<n;i++) { for (j=0;j<n;j++) fprintf(op,"%d\\t",A[n*i+j]); fprintf(op,"\\n"); } fclose(op); return 0; } int PrintMat(int* A, int n) { int i,j; for (i=0;i<n;i++) { for (j=0;j<n;j++) printf("%d\\t", A[i*n+j]); printf("\\n"); } return 0; } void* findPath(void* arg) { int i,j,k,temp; int rank = (int)arg; int start = rank * n / num_thrd; int end = (rank + 1) * n / num_thrd; for(k = 0; k < n; k++) { for(i = start; i < end; i++) { for(j = 0; j < n; j++) { pthread_mutex_lock(&k_threshold_mutex); A_flag[i*n+j]++; pthread_mutex_unlock(&k_threshold_mutex); while(A_flag[i*n+(k)] < (k) || A_flag[(k)*n+j] < (k)) { continue; } if ((temp=A[i*n+k]+A[k*n+j])<A[i*n+j]) A[i*n+j]=temp; } } } return 0; } int main (int argc, char* argv[]) { double start,end; pthread_t* thread; int i,j; FILE * fp; if (argc < 3) { printf("Usage ./lab2 num_cities num_thrds\\n"); return 1; } n=strtol(argv[1], 0, 10); num_thrd = strtol(argv[2], 0, 10); Loaddata(A, n); for (i = 0; i < 1000000; i++) A_flag[i] = 0; thread = (pthread_t*) malloc((num_thrd)*sizeof(pthread_t)); GET_TIME(start); for(i = 0; i < num_thrd; ++i) { if(pthread_create(&thread[i], 0, &findPath, (void*)i)) { printf("Could not create thread %d\\n", i); free(thread); return -1; } } for (i = 0; i < num_thrd ; i++) pthread_join (thread[i], 0); GET_TIME(end); Savedata(A, n); printf("Computation time: %F\\n",(end - start)); return 0; }
1
#include <pthread.h> struct fuse_worker { struct fuse_worker *prev; struct fuse_worker *next; pthread_t thread_id; size_t bufsize; char *buf; struct fuse_mt *mt; }; struct fuse_mt { pthread_mutex_t lock; int numworker; int numavail; struct fuse_session *se; struct fuse_chan *prevch; struct fuse_worker main; sem_t finish; int exit; int error; }; static void list_add_worker(struct fuse_worker *w, struct fuse_worker *next) { struct fuse_worker *prev = next->prev; w->next = next; w->prev = prev; prev->next = w; next->prev = w; } static void list_del_worker(struct fuse_worker *w) { struct fuse_worker *prev = w->prev; struct fuse_worker *next = w->next; prev->next = next; next->prev = prev; } static int fuse_start_thread(struct fuse_mt *mt); static void *fuse_do_work(void *data) { struct fuse_worker *w = (struct fuse_worker *) data; struct fuse_mt *mt = w->mt; while (!fuse_session_exited(mt->se)) { int isforget = 0; struct fuse_chan *ch = mt->prevch; int res = fuse_chan_recv(&ch, w->buf, w->bufsize); if (res == -EINTR) continue; if (res <= 0) { if (res < 0) { fuse_session_exit(mt->se); mt->error = -1; } break; } pthread_mutex_lock(&mt->lock); if (mt->exit) { pthread_mutex_unlock(&mt->lock); return 0; } if (((struct fuse_in_header *) w->buf)->opcode == FUSE_FORGET) isforget = 1; if (!isforget) mt->numavail--; if (mt->numavail == 0) fuse_start_thread(mt); pthread_mutex_unlock(&mt->lock); fuse_session_process(mt->se, w->buf, res, ch); pthread_mutex_lock(&mt->lock); if (!isforget) mt->numavail++; if (mt->numavail > 10) { if (mt->exit) { pthread_mutex_unlock(&mt->lock); return 0; } list_del_worker(w); mt->numavail--; mt->numworker--; pthread_mutex_unlock(&mt->lock); pthread_detach(w->thread_id); free(w->buf); free(w); return 0; } pthread_mutex_unlock(&mt->lock); } sem_post(&mt->finish); pause(); return 0; } static int fuse_start_thread(struct fuse_mt *mt) { sigset_t oldset; sigset_t newset; int res; struct fuse_worker *w = malloc(sizeof(struct fuse_worker)); if (!w) { fprintf(stderr, "fuse: failed to allocate worker structure\\n"); return -1; } memset(w, 0, sizeof(struct fuse_worker)); w->bufsize = fuse_chan_bufsize(mt->prevch); w->buf = malloc(w->bufsize); w->mt = mt; if (!w->buf) { fprintf(stderr, "fuse: failed to allocate read buffer\\n"); free(w); return -1; } sigemptyset(&newset); sigaddset(&newset, SIGTERM); sigaddset(&newset, SIGINT); sigaddset(&newset, SIGHUP); sigaddset(&newset, SIGQUIT); pthread_sigmask(SIG_BLOCK, &newset, &oldset); res = pthread_create(&w->thread_id, 0, fuse_do_work, w); pthread_sigmask(SIG_SETMASK, &oldset, 0); if (res != 0) { fprintf(stderr, "fuse: error creating thread: %s\\n", strerror(res)); free(w->buf); free(w); return -1; } list_add_worker(w, &mt->main); mt->numavail ++; mt->numworker ++; return 0; } static void fuse_join_worker(struct fuse_mt *mt, struct fuse_worker *w) { pthread_join(w->thread_id, 0); pthread_mutex_lock(&mt->lock); list_del_worker(w); pthread_mutex_unlock(&mt->lock); free(w->buf); free(w); } int fuse_session_loop_mt(struct fuse_session *se) { int err; struct fuse_mt mt; struct fuse_worker *w; memset(&mt, 0, sizeof(struct fuse_mt)); mt.se = se; mt.prevch = fuse_session_next_chan(se, 0); mt.error = 0; mt.numworker = 0; mt.numavail = 0; mt.main.thread_id = pthread_self(); mt.main.prev = mt.main.next = &mt.main; sem_init(&mt.finish, 0, 0); fuse_mutex_init(&mt.lock); pthread_mutex_lock(&mt.lock); err = fuse_start_thread(&mt); pthread_mutex_unlock(&mt.lock); if (!err) { while (!fuse_session_exited(se)) sem_wait(&mt.finish); for (w = mt.main.next; w != &mt.main; w = w->next) pthread_cancel(w->thread_id); mt.exit = 1; pthread_mutex_unlock(&mt.lock); while (mt.main.next != &mt.main) fuse_join_worker(&mt, mt.main.next); err = mt.error; } pthread_mutex_destroy(&mt.lock); sem_destroy(&mt.finish); fuse_session_reset(se); return err; }
0
#include <pthread.h> pthread_mutex_t wait; short mother_finished = 0; short check_if_full_plates(short* table_plates) { short full_plate = 0; int i; pthread_mutex_lock(&wait); for(i = 0; i < 4; i++) { if(table_plates[i] == 1) { return 1; } } pthread_mutex_unlock(&wait); return 0; } void* maika_mu_gotvi(void* table_plates) { short* plates = (short*) table_plates; int flour_weight = 1000; int plate = 0; while(flour_weight > 0) { if(plate == 4) { plate = 0; } int random_flour = rand() % 100 + 1; if(flour_weight >= random_flour && plates[plate] == 0) { pthread_mutex_lock(&wait); flour_weight -= random_flour; printf("%d", flour_weight); usleep(random_flour*10000); plates[plate] = 1; pthread_mutex_unlock(&wait); } plate++; } mother_finished = 1; pthread_exit(0); } void* toi_qde(void* table_plates) { short* plates = (short*) table_plates; int plate = 0; int i_am_eating = rand() % 100 + 1; printf("%d ------------- %d\\n", mother_finished, check_if_full_plates(plates)); while(mother_finished == 0 && check_if_full_plates(plates) == 1) { if(plate == 4) { plate = 0; } if(plates[plate] == 1) { pthread_mutex_lock(&wait); printf("QM MA"); usleep(i_am_eating * 10000); plates[plate] = 0; pthread_mutex_unlock(&wait); } plate++; } } int main() { pthread_mutex_init(&wait, 0); pthread_t ivancho, maika_mu; short table_plates[4]; pthread_create(&maika_mu, 0, maika_mu_gotvi, (void*) table_plates); pthread_create(&ivancho, 0, toi_qde, (void*) table_plates); pthread_join(maika_mu, 0); pthread_join(ivancho, 0); pthread_mutex_destroy(&wait); return 0; }
1
#include <pthread.h> pthread_mutex_t *chopstick; void pickup(int me) { if (me == 10) { pthread_mutex_lock(&chopstick[((me + 1) % 5)]); pthread_mutex_lock(&chopstick[me]); } else { pthread_mutex_lock(&chopstick[me]); pthread_mutex_lock(&chopstick[((me + 1) % 5)]); } } void putdown(int me) { pthread_mutex_unlock(&chopstick[me]); pthread_mutex_unlock(&chopstick[((me + 1) % 5)]); } void func(int me) { srand(time(0)); while (1) { printf("philosopher %d thinking...\\n", me); usleep(rand() % 10); pickup(me); printf("philosopher %d eating...\\n", me); usleep(rand() % 10); putdown(me); } } int main(void) { int i; int fd; pid_t pid; if ((fd = open("/dev/zero", O_RDWR)) < 0) { perror("open()"); exit(1); } if ((chopstick = mmap(0, sizeof(pthread_mutex_t) * 5, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) { perror("mmap()"); exit(1); } for (i = 0; i < 5; i++) { pthread_mutex_init(&chopstick[i], 0); } for (i = 0; i < 5 - 1; i++) { pid = fork(); if (pid < 0) { perror("fork()"); exit(1); } if (pid == 0) { func(i); exit(0); } } func(i); munmap(chopstick, sizeof(pthread_mutex_t) * 5); close(fd); return 0; }
0
#include <pthread.h> static int iTThreads = 1; static int iRThreads = 1; static int data1Value = 0; static int data2Value = 0; pthread_mutex_t *data1Lock; pthread_mutex_t *data2Lock; void lock(pthread_mutex_t *); void unlock(pthread_mutex_t *); void *funcA(void *param) { pthread_mutex_lock(data1Lock); data1Value = 1; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); data2Value = data1Value + 1; pthread_mutex_unlock(data2Lock); return 0; } void *funcB(void *param) { int t1 = -1; int t2 = -1; pthread_mutex_lock(data1Lock); if (data1Value == 0) { pthread_mutex_unlock(data1Lock); return 0; } t1 = data1Value; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); t2 = data2Value; pthread_mutex_unlock(data2Lock); if (t2 != (t1 + 1)) { fprintf(stderr, "Bug found!\\n"); assert(0); } return 0; } int main(int argc, char *argv[]) { int i,err; if (argc != 1) { if (argc != 3) { } else { } } data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); if (0 != (err = pthread_mutex_init(data1Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } if (0 != (err = pthread_mutex_init(data2Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } iTThreads = 100; iRThreads = 100; pthread_t tPool[100]; pthread_t rPool[100]; for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) { fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) { fprintf(stderr, "Error [%d] found creating read thread.\\n", err); exit(-1); } } for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_join(tPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_join(rPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } return 0; } void lock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_lock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err); exit(-1); } } void unlock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_unlock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err); exit(-1); } }
1
#include <pthread.h> pthread_t pthread_id[2]; pthread_mutex_t mutex1, mutex2; int status; void *f_thread_1(void *ptr){ pthread_mutex_lock(&mutex1); printf("je suis le pthread 1 %d\\n",pthread_self()); pthread_exit(0); } void *f_thread_2(void *ptr){ pthread_mutex_lock(&mutex2); sleep(3); printf("je suis le pthread 2 %d\\n",pthread_self()); pthread_exit(0); } main(){ int i; pthread_mutex_init(&mutex1,0); pthread_mutex_init(&mutex2,0); pthread_create(pthread_id,0,f_thread_1,(void *)&i); pthread_create(pthread_id+1,0,f_thread_2,(void *)&i); printf("les pthread %d et %d sont creees \\n",pthread_id[0], pthread_id[1]); pthread_mutex_unlock(&mutex1); pthread_join(pthread_id[0],0); printf("la pthread 1 %d est terminee \\n", pthread_id[1]); pthread_mutex_unlock(&mutex2); pthread_join(pthread_id[1],0); printf("la pthread 2 %d est terminee \\n",pthread_id[0]); }
0
#include <pthread.h> pthread_mutex_t mutex; void err_thread(int ret, char *str) { if (ret != 0) { fprintf(stderr, "%s:%s\\n", str, strerror(ret)); pthread_exit(0); } } void *tfn(void *arg) { srand(time(0)); while (1) { pthread_mutex_lock(&mutex); printf("hello "); sleep(rand() % 3); printf("world\\n"); pthread_mutex_unlock(&mutex); sleep(rand() % 3); } return 0; } int main(void) { int flag = 5; pthread_t tid; srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_create(&tid, 0, tfn, 0); while (flag--) { pthread_mutex_lock(&mutex); printf("HELLO "); sleep(rand() % 3); printf("WORLD\\n"); pthread_mutex_unlock(&mutex); sleep(rand() % 3); } pthread_cancel(tid); pthread_join(tid, 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> static int fd ; int IsBusy(void) { unsigned short wdata, rdata; wdata = 0x0200; write(fd ,&wdata,2); wdata = 0x0200 | 0x0400; write(fd ,&wdata,2); read(fd,&rdata ,2); wdata = 0x0200; write(fd,&wdata,2); if (rdata & 0x0080) return 1; return 0; } int tlcd_writeCmd(unsigned short cmd) { unsigned short wdata ; if ( IsBusy()) return 0; wdata = cmd; write(fd ,&wdata,2); wdata = cmd | 0x0400; write(fd ,&wdata,2); wdata = cmd ; write(fd ,&wdata,2); return 1; } int setDDRAMAddr(int x , int y) { unsigned short cmd = 0; if(IsBusy()) { perror("setDDRAMAddr busy error.\\n"); return 0; } if ( y == 1 ) { cmd = 0x0000 +x; } else if(y == 2 ) { cmd = 0x0040 +x; } else return 0; if ( cmd >= 0x80) return 0; if (!tlcd_writeCmd(cmd | 0x0080)) { perror("setDDRAMAddr error\\n"); return 0; } usleep(1000); return 1; } int displayMode(int bCursor, int bCursorblink, int blcd ) { unsigned short cmd = 0; if ( bCursor) { cmd = 0x0002; } if (bCursorblink ) { cmd |= 0x0001; } if ( blcd ) { cmd |= 0x0004; } if (!tlcd_writeCmd(cmd | 0x0008)) return 0; return 1; } int writeCh(unsigned short ch) { unsigned short wdata =0; if ( IsBusy()) return 0; wdata = 0x0100 | ch; write(fd ,&wdata,2); wdata = 0x0100 | ch | 0x0400; write(fd ,&wdata,2); wdata = 0x0100 | ch; write(fd ,&wdata,2); usleep(1000); return 1; } int setCursorMode(int bMove , int bRightDir) { unsigned short cmd = 0x0004; if (bMove) cmd |= 0x0001; if (bRightDir) cmd |= 0x0002; if (!tlcd_writeCmd(cmd)) return 0; return 1; } int functionSet(void) { unsigned short cmd = 0x0038; if (!tlcd_writeCmd(cmd)) return 0; return 1; } int writeStr(char* str) { unsigned char wdata; int i; for(i =0; i < strlen(str) ;i++ ) { if (str[i] == '_') wdata = (unsigned char)' '; else wdata = str[i]; writeCh(wdata); } return 1; } int clearScreen(int nline) { int i; if (nline == 0) { if(IsBusy()) { perror("clearScreen error\\n"); return 0; } if (!tlcd_writeCmd(0x0001)) return 0; return 1; } else if (nline == 1) { setDDRAMAddr(0,1); for(i = 0; i <= 16 ;i++ ) { writeCh((unsigned char)' '); } setDDRAMAddr(0,1); } else if (nline == 2) { setDDRAMAddr(0,2); for(i = 0; i <= 16 ;i++ ) { writeCh((unsigned char)' '); } setDDRAMAddr(0,2); } return 1; } extern pthread_mutex_t mtx; extern int level; void* text_lcd(void* rgb_arr) { char* strWtext; unsigned int* out_arr = (unsigned int*)rgb_arr; unsigned int vR, vG, vB; vR = out_arr[0]; vG = out_arr[1]; vB = out_arr[2]; strWtext = (char*)malloc(sizeof(char)); fd = open("/dev/cntlcd",O_RDWR); if ( fd < 0 ) { perror("driver open error.\\n"); exit(1); } sprintf(strWtext, " R%03d_G%03d_B%03d", vR, vG, vB); while(level!=6) { pthread_mutex_lock(&mtx); functionSet(); clearScreen(0); displayMode(1, 1, 1); setDDRAMAddr(0, 2); writeStr(strWtext); pthread_mutex_unlock(&mtx); usleep(100000); } close(fd); return; }
0
#include <pthread.h> static int valueget=0; static char nameget='P'; struct elem{ char c; int integer; }; struct buffer{ struct elem content[16]; int readp; int writep; int counter; pthread_mutex_t bufferlocker; pthread_cond_t bufferwait; }; static struct buffer b; void buffer_init(struct buffer b) { b.readp=0; b.writep=0; b.counter=0; pthread_mutexattr_t mymutexattr1; pthread_mutexattr_init(&mymutexattr1); pthread_mutex_init(&(b.bufferlocker), &mymutexattr1); pthread_mutexattr_destroy(&mymutexattr1); pthread_condattr_t mycondattr2; pthread_condattr_init(&mycondattr2); pthread_cond_init(&(b.bufferwait), &mycondattr2); pthread_condattr_destroy(&mycondattr2); } int enqueue(char name, int value) { pthread_mutex_lock(&(b.bufferlocker)); b.writep=(b.writep)%16; int fwrp=b.writep; while (b.counter>=16) { pthread_cond_wait(&(b.bufferwait), &(b.bufferlocker)); } b.content[fwrp].c=name; b.content[fwrp].integer=value; b.writep++; b.counter++; printf("enqueue %c %d\\n",b.content[fwrp].c,b.content[fwrp].integer); fflush(stdout); pthread_cond_broadcast(&(b.bufferwait)); pthread_mutex_unlock(&(b.bufferlocker)); return 0; } void dequeue(void) { pthread_mutex_lock(&(b.bufferlocker)); b.readp=(b.readp)%16; int frdp=b.readp; while (b.counter<=0) { pthread_cond_wait(&(b.bufferwait), &(b.bufferlocker)); } nameget=b.content[frdp].c; valueget=b.content[frdp].integer; b.readp++; b.counter--; printf(" dequeue %c %d \\n",nameget,valueget); fflush(stdout); pthread_cond_broadcast(&(b.bufferwait)); pthread_mutex_unlock(&(b.bufferlocker)); } int comsumerth(void){ int i=0; for (i=0;i<3000;i++) { dequeue(); } return 0; } int producerth1(void){ int i=0; char p='p'; for (i=0; i<1000; i++) { enqueue(p, i+1000); } return 0; } int producerth2(void){ int i=0; char p='p'; for (i=0; i<1000; i++) { enqueue(p,2000+i); } return 0; } int producerth3(void){ int i=0; char p='p'; for (i=0; i<1000; i++) { enqueue(p, i+3000); } return 0; } int main() { pthread_t thread1, thread2,thread3,thread4, main_id; main_id=pthread_self(); buffer_init(b); pthread_create( &thread1, 0, &producerth1, 0); pthread_create( &thread2, 0, &producerth2, 0); pthread_create( &thread3, 0, &producerth3, 0); pthread_create( &thread4, 0, &comsumerth, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); pthread_join( thread3, 0); pthread_join( thread4, 0); exit(0); }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t can_write = PTHREAD_COND_INITIALIZER; pthread_cond_t can_read = PTHREAD_COND_INITIALIZER; char arr[10] = {0}; int in_pos = 0; int out_pos = 0; void* do_it_a(void* p) { char c = 'a'; for(; c <= 'z'; c++) { pthread_mutex_lock(&lock); if(((in_pos + 1)%10) == out_pos) { printf("queue is full(a)\\n"); pthread_mutex_lock(&lock); } pthread_cond_wait(&can_write,&lock); arr[in_pos] = c; in_pos = (in_pos + 1) % 10; pthread_cond_signal(&can_read); pthread_mutex_unlock(&lock); } } void* do_it_b(void* p) { char c = 'A'; for(; c <= 'Z'; c++) { pthread_mutex_lock(&lock); if(((in_pos + 1)%10) == out_pos) { printf("%d\\n",(in_pos+1)%10); printf("%d\\n",out_pos); printf("queue is full(b)\\n"); pthread_mutex_unlock(&lock); } arr[in_pos] = c; in_pos = (in_pos + 1) % 10; pthread_cond_signal(&can_read); pthread_mutex_unlock(&lock); } } void* do_it_c(void* p) { int i = 0; char c = 'A'; char box; for(; i <= 52; i++) { pthread_mutex_lock(&lock); if(in_pos == out_pos) { printf("queue is empty\\n"); pthread_mutex_unlock(&lock); } pthread_cond_wait(&can_read,&lock); for(; c <= 'Z'; c++) { if(arr[out_pos] == c) { printf("big printf:%c\\n",c); fflush(stdout); out_pos = ((out_pos + 1) % 10); } } pthread_cond_signal(&can_write); pthread_mutex_unlock(&lock); } } void* do_it_d(void* p) { int i = 0; char c = 'a'; char box; for(; i <= 52; i++) { pthread_mutex_lock(&lock); if(in_pos == out_pos) { printf("queue is empty\\n"); pthread_mutex_unlock(&lock); } pthread_cond_wait(&can_read,&lock); for(; c <= 'z'; c++) { if(arr[out_pos] == c) { printf("small printf:%c\\n",c); fflush(stdout); out_pos = ((out_pos + 1) % 10); } } pthread_cond_signal(&can_write); pthread_mutex_unlock(&lock); } } int main() { printf("%d\\n",1%10); pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4; pthread_create(&t1,0,do_it_a,0); pthread_create(&t1,0,do_it_b,0); pthread_create(&t1,0,do_it_c,0); pthread_create(&t1,0,do_it_d,0); pthread_join(t1,0); pthread_join(t2,0); pthread_join(t3,0); pthread_join(t4,0); return 0; }
0
#include <pthread.h> int getAleatorio(int maximo); pthread_mutex_t sum_mutex; int *arr_cuentas; int *arr_cuentas_estado; int numeroDeHilos, cantidad_tiempo_a_correr, numero_cuentas, valor_inicial; void *calcularTransferencias(){ int cuentaA=getAleatorio(numero_cuentas); int cuentaB=getAleatorio(numero_cuentas); while( arr_cuentas_estado[cuentaA] != 0 && arr_cuentas_estado[cuentaB] != 0 ){ cuentaA=getAleatorio(numero_cuentas); cuentaB=getAleatorio(numero_cuentas); } pthread_mutex_lock(&sum_mutex); arr_cuentas_estado[cuentaA] = 1; arr_cuentas_estado[cuentaB] = 1; pthread_mutex_unlock(&sum_mutex); int monto = 0; time_t start = time(0); for(;;) { monto = getAleatorio( arr_cuentas[cuentaA] ); arr_cuentas[cuentaA] = arr_cuentas[cuentaA] - monto; arr_cuentas[cuentaB] = arr_cuentas[cuentaB] + monto; monto = getAleatorio( arr_cuentas[cuentaB] ); arr_cuentas[cuentaB] = arr_cuentas[cuentaB] - monto; arr_cuentas[cuentaA] = arr_cuentas[cuentaA] + monto; if(time(0) > start + cantidad_tiempo_a_correr){ break; } } pthread_mutex_lock(&sum_mutex); arr_cuentas_estado[cuentaA] = 0; arr_cuentas_estado[cuentaB] = 0; pthread_mutex_unlock(&sum_mutex); int resu=0; return (void*)resu; } int getAleatorio(int maximo){ srand(time(0)); int result = rand() % maximo; return result; } int main (int argn, char *arg[]){ int x = 0; if (sscanf (arg[1], "%i", &numeroDeHilos) !=1 ) { printf ("error - not an integer"); } if (sscanf (arg[2], "%i", &cantidad_tiempo_a_correr) !=1 ) { printf ("error - not an integer"); } if (sscanf (arg[3], "%i", &numero_cuentas) !=1 ) { printf ("error - not an integer"); } if (sscanf (arg[4], "%i", &valor_inicial) !=1 ) { printf ("error - not an integer"); } pthread_mutex_init(&sum_mutex, 0); arr_cuentas = (int *)malloc(numero_cuentas*sizeof(int)); for ( x = 0; x < numero_cuentas; x++ ){ arr_cuentas[x] = valor_inicial; } arr_cuentas_estado = (int *)malloc(numero_cuentas*sizeof(int)); for ( x = 0; x < numero_cuentas; x++ ){ arr_cuentas_estado[x] = 0; } pthread_t hilos[numeroDeHilos]; for ( x = 0; x < numeroDeHilos; x++ ){ pthread_create (&hilos[x], 0, &calcularTransferencias, 0); } int nada; for ( x = 0; x < numeroDeHilos; x++ ){ pthread_join(hilos[x],(void*)&nada); } int balanceTotal=0; for ( x = 0; x < numero_cuentas; x++ ){ printf("Valor de la cuenta %d: %d\\n", x, arr_cuentas[x]); balanceTotal = balanceTotal + arr_cuentas[x]; } printf("\\nBalance Total%d: \\n", balanceTotal); pthread_mutex_destroy(&sum_mutex); pthread_exit(0); exit(0); }
1
#include <pthread.h> struct node *next; int data; } Node; struct node *head, *tail; } Queue; void initialize_queue(void); void enqueue(int val); int dequeue(int *extractedValue); int isEmpty(); void printContent(); int sumOfAllElements(); void clearQueue(); static Queue *q; pthread_mutex_t headLock; pthread_mutex_t tailLock; void initialize_queue(void){ Node *dummyNode = malloc(sizeof(Node)); q = malloc(sizeof(Queue)); q->head = dummyNode; q->tail = dummyNode; pthread_mutex_init(&headLock, 0); pthread_mutex_init(&tailLock, 0); } void enqueue(int val){ Node *newNode = malloc(sizeof(Node)); newNode->data = val; pthread_mutex_lock(&tailLock); q->tail->next = newNode; q->tail = newNode; pthread_mutex_unlock(&tailLock); } int dequeue(int *extractedValue){ pthread_mutex_lock(&headLock); if(isEmpty()){ pthread_mutex_unlock(&headLock); return 1; } *extractedValue = q->head->next->data; struct node *temp = q->head->next; free(q->head); q->head = temp; pthread_mutex_unlock(&headLock); return 0; } int isEmpty(){ return q->head == q->tail; } void printContent(){ if(isEmpty()) return; Node *node = q->head->next; while(node != q->tail){ printf("%i ", node->data); node = node->next; } printf("%i \\n", node->data); } int sumOfAllElements(){ if(isEmpty()) return 0; int sum = 0; Node *node = q->head->next; while(node != q->tail){ sum += node->data; node = node->next; } sum += node->data; return sum; } void clearQueue(){ int *dummy = malloc(sizeof(int)); while(!isEmpty()){ dequeue(dummy); } free(dummy); }
0
#include <pthread.h> pthread_t id[3]; int clock_t_1=0, clock_t_2=0, clock_t_3=0; int sender = 1; pthread_mutex_t mutex_var; void *increment1(void *interval) { int *intr= (int*)interval; while(1) { sleep(2); clock_t_1 = clock_t_1 + *intr; printf("\\nClock 1 = %d\\n",clock_t_1); } } void *increment2(void *interval) { int *intr=(int*)interval; while(1) { sleep(2); clock_t_2 = clock_t_2 + *intr; printf("\\nClock 2 = %d\\n",clock_t_2); } } void *increment3(void *interval) { int *intr= (int*)interval; while(1) { sleep(2); clock_t_3 = clock_t_3 + *intr; printf("\\nClock 3 = %d\\n",clock_t_3); } } void* clock1(void *interval) { int *intr = (int*)interval; pthread_t id1; pthread_create(&id1,0,&increment1,interval); while(1) { sleep(5); pthread_mutex_lock(&mutex_var); printf("\\nThread 1 received message at %d from %d",clock_t_1, sender); if(sender == 2 && clock_t_1 < clock_t_2) { clock_t_1 = clock_t_2 + 1; printf("\\nThread 1 updates its clock at %d",clock_t_1); } if(sender==3 && clock_t_1<clock_t_3) { clock_t_1 = clock_t_3 + 1; printf("\\nThread 1 updated its clock at %d",clock_t_1); } sender =1; pthread_mutex_unlock(&mutex_var); printf("\\nThread 1 sends message at %d",clock_t_1); } pthread_join(id1,0); } void* clock2(void *interval) { int *intr = (int*)interval; pthread_t id2; pthread_create(&id2,0,&increment2,interval); while(1) { sleep(5); pthread_mutex_lock(&mutex_var); printf("\\nThread 2 received message at %d from %d",clock_t_2, sender); if(sender == 1 && clock_t_2 < clock_t_1) { clock_t_2 = clock_t_1 + 1; printf("\\nThread 2 updates its clock at %d",clock_t_2); } if(sender==3 && clock_t_2<clock_t_3) { clock_t_2 = clock_t_3 + 1; printf("\\nThread 2 updated its clock at %d",clock_t_2); } sender =2; pthread_mutex_unlock(&mutex_var); printf("\\nThread 2 sends message at %d",clock_t_2); } pthread_join(id2,0); } void* clock3(void *interval) { int *intr = (int*)interval; pthread_t id3; pthread_create(&id3,0,&increment3,interval); while(1) { sleep(5); pthread_mutex_lock(&mutex_var); printf("\\nThread 3 received message at %d from %d",clock_t_3, sender); if(sender == 1 && clock_t_3 < clock_t_1) { clock_t_3 = clock_t_1 + 1; printf("\\nThread 3 updates its clock at %d",clock_t_3); } if(sender==2 && clock_t_3<clock_t_2) { clock_t_3 = clock_t_2 + 1; printf("\\nThread 3 updated its clock at %d",clock_t_3); } sender =3; pthread_mutex_unlock(&mutex_var); printf("\\nThread 3 sends message at %d",clock_t_3); } pthread_join(id3,0); } int main() { int interval[3]; interval[0]=6; interval[1]=8; interval[2]=10; pthread_create(&id[0],0,&clock1,(void*)&interval[0]); pthread_create(&id[1],0,&clock2,(void*)&interval[1]); pthread_create(&id[2],0,&clock3,(void*)&interval[2]); pthread_join(id[0],0); pthread_join(id[1],0); pthread_join(id[2],0); }
1
#include <pthread.h> int ActivateROEReal() { pthread_mutex_lock(&roe.mx); if(roe.active == FALSE) { } roe.active = TRUE; pthread_mutex_unlock(&roe.mx); record("ROE Active\\n"); return 0; } int deactivateReal() { pthread_mutex_lock(&roe.mx); if(roe.active == TRUE) { } roe.active = FALSE; pthread_mutex_lock(&roe.mx); record("ROE Deactivated\\n"); } int exitDefaultReal() { record("Exiting Default Mode"); return 0; } int selftestModeReal() { record("Entering Self Test Mode"); return 0; } int stimOnReal() { record("Entering Stims Mode"); return 0; } int stimOffReal() { record("Exiting Stims Mode"); return 0; } int resetReal() { record("Reseting to Default Mode"); return 0; } int readOutReal(char* block,int delay) { record("Reading Out CCD's"); return 0; } int flushReal() { record("Flushing CCD's"); return 0; } int getHKReal(char* hkparam) { return 0xFF; } char* getAEReal() { } int setAEReal(char* paramstring) { record("Setting AE Params"); return 0; } int manualWriteReal(char* msg, int size) { return 0; }
0
#include <pthread.h> struct fdlist_t { uintptr_t bt[15]; int bt_depth; int fd; struct fdlist_t *next; int allocated; } ; pthread_mutex_t osal_debug_fdleak_mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t osal_debug_fdleak_con = PTHREAD_COND_INITIALIZER; char osal_debug_fdleak_event; static unsigned int fdleak_count = 0; static fdlist_t *head = 0; static real_open_type __real_open = 0; static real_pipe_type __real_pipe= 0; static real_socket_type __real_socket= 0; static real_mmap_type __real_mmap= 0; static real_close_type __real_close= 0; static inline void add(int fd_value) { fdlist_t *fdlist; fdlist = (fdlist_t *) malloc(sizeof(fdlist_t)); if (!fdlist) return; fdlist->allocated = 0x7abc0fb5; fdlist->bt_depth = 0; fdlist->fd = fd_value; pthread_mutex_lock(&osal_debug_fdleak_mut); fdlist->bt_depth = function_stacktrace(fdlist->bt, 15); fdlist->next = head; head = fdlist; fdleak_count++; pthread_mutex_unlock(&osal_debug_fdleak_mut); } void fdleak_dump_list() { fdlist_t *del; int cnt, cnt_all = 0; struct map_info_holder *p_map_info; struct fdlist_t *temp; temp = head; pthread_mutex_lock(&osal_debug_fdleak_mut); pid_t c_pid = getpid(); p_map_info = lib_map_create(c_pid); while (temp != 0) { printf("leaked fd %d\\n",temp->fd); print_backtrace(p_map_info, temp->bt, temp->bt_depth); temp = temp->next; } lib_map_destroy(p_map_info); pthread_mutex_unlock(&osal_debug_fdleak_mut); fdleak_count = 0; } int __open(const char* dev_name, int flags, ...) { int fd_value; mode_t mode = 0; if ((flags & O_CREAT) != 0) { va_list args; __builtin_va_start((args)); mode = (mode_t)__builtin_va_arg((args)); ; } fd_value = open(dev_name, flags, mode); if (errno == EMFILE) { printf( "FATAL during open %s Restart camera daemon !!!",strerror(errno)); raise(SIGABRT); raise(SIGKILL); } if (fd_value > 0) { add( fd_value); return fd_value; } return fd_value; } int __pipe(int fd[]) { int ret_value; ret_value = pipe(fd); if (errno == EMFILE) { printf( "FATAL during pipe creation %s Restart camera daemon !!!",strerror(errno)); raise(SIGABRT); raise(SIGKILL); } if (ret_value >= 0) { add( fd[0]); add( fd[1]); return ret_value; } return ret_value; } int __socket(int domain, int type, int protocol) { int ds_fd ; ds_fd = socket(domain, type, protocol); if (errno == EMFILE) { printf( "FATAL during socket create %s Restart camera daemon !!!",strerror(errno)); raise(SIGABRT); raise(SIGKILL); } if (ds_fd > 0) { add( ds_fd); return ds_fd; } return ds_fd; } void* __mmap(void* addr, size_t size, int prot, int flags, int fd, off_t offset) { void* ret; ret = mmap(addr, size, prot, flags, fd, offset); if (errno == EMFILE) { printf( "FATAL during mmap %s Restart camera daemon !!!",strerror(errno)); raise(SIGABRT); raise(SIGKILL); } if (fd > 0) { add( fd); return ret; } return ret; } void delete_node(int fd_value) { static fdlist_t *temp,*prev; temp = head; while (temp != 0) { if (temp->fd != fd_value) { prev = temp; temp = temp->next; } else { fdleak_count--; if (temp == head) { head = temp->next; free(temp); return; }else { prev->next = temp->next; free(temp); return; } } } } static int __close(int fd_value) { pthread_mutex_lock(&osal_debug_fdleak_mut); delete_node(fd_value); pthread_mutex_unlock(&osal_debug_fdleak_mut); return (close(fd_value)); } int __wrap_open(const char* dev_name, int flags, ...) { mode_t mode = 0; if ((flags & O_CREAT) != 0) { va_list args; __builtin_va_start((args)); mode = (mode_t)__builtin_va_arg((args)); ; } return __real_open(dev_name, flags, mode); } int __wrap_pipe(int *fd) { return __real_pipe(fd); } int __wrap_socket(int domain, int type, int protocol) { return __real_socket(domain,type,protocol); } void* __wrap_mmap(void* addr, size_t size, int prot, int flags, int fd, off_t offset) { return __real_mmap(addr, size, prot, flags, fd, offset); } int __wrap_close(int fd_value) { return __real_close(fd_value); } static void init(void) { __real_open = open; __real_pipe = pipe; __real_socket = socket; __real_mmap = mmap; __real_close = close; } void osal_degug_enable_fdleak_trace() { __real_open = __open; __real_pipe = __pipe; __real_socket = __socket; __real_mmap = __mmap; __real_close = __close; } void osal_degug_dump_fdleak_trace() { __real_open = open; __real_pipe = pipe; __real_socket = socket; __real_mmap = mmap; __real_close = close; if (fdleak_count) { printf("FATAL fdleak found in camera daemon %d", fdleak_count); fdleak_dump_list(); } } static void finish(void) { printf("fdleak lib deinit.\\n"); if (fdleak_count) fdleak_dump_list(); }
1
#include <pthread.h> void *thread_function(void *); char *trimr(char *); void print_usage(const char *); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; unsigned long int total_lines = 0; const char *filename; const char *user_process; unsigned short int max_threads = DEF_THREADS; unsigned long int map[MAX_THREADS]; int main(const int argc, const char *argv[]){ if (argc < 1 + 2){ print_usage(argv[0]); exit(100); } filename = argv[1]; user_process = argv[2]; if (argc >= 1 + 3){ max_threads = atoi(argv[3]); if (max_threads < 1) max_threads = DEF_THREADS; if (max_threads > MAX_THREADS) max_threads = MAX_THREADS; } fprintf(stderr, "%-15s : %s\\n", "Input file", filename ); fprintf(stderr, "%-15s : %s\\n", "User process", user_process ); fprintf(stderr, "\\n"); if ( strcmp(filename, "-") ){ split(filename, max_threads, MIN_FILE_PART, map); fprintf(stderr, "Threads dump\\n"); unsigned short int j; for (j = 0; j < max_threads; j++){ if (! map[j + 1]) break; fprintf(stderr, "\\t%04d @ %10ld %10ld\\n", j, map[j], map[j + 1]); } max_threads = j; } fprintf(stderr, "%-15s : %d\\n", "Total threads", max_threads ); fprintf(stderr, "\\n"); pthread_t thread_id[MAX_THREADS]; int data[MAX_THREADS]; unsigned short int i; for (i=0; i < max_threads; i++){ data[i] = i; pthread_create( &thread_id[i], 0, thread_function, (void *) & data[i] ); sleep(rand() % 2); } for (i=0; i < max_threads; i++){ pthread_join( thread_id[i], 0 ); fprintf(stderr, "%4d more thread to go...\\n", (max_threads - i - 1) ); } fprintf(stderr, "\\n"); fprintf(stderr, "Total lines %ld.\\n", total_lines); return 0; } void *thread_function(void *data){ const int no = *( (int *) data ); char buff[MAX_BUFFER]; unsigned long int lcounter = 0; unsigned long int lfilesize = 0; FILE *F = stdin; if ( strcmp(filename, "-") ){ F = fopen(filename, "r"); if (! F){ fprintf(stderr, "ERROR: Can not open the input file %s...\\n", filename); return 0; } fseek(F, map[no], 0); } FILE *P = popen(user_process, "w"); if (! P){ fprintf(stderr, "ERROR: Can not open the user process %s...\\n", user_process); return 0; } fprintf(stderr, "Thread %04d started...\\n", no); unsigned long int filesize = strcmp(filename, "-") ? map[no + 1] - map[no] : 0 ; while(! feof(F)){ const char *data = fgets(buff, MAX_BUFFER, F); if (data) fputs(data, P); if (data == 0) break; lcounter++; lfilesize = lfilesize + strlen(data); if (lcounter % PROGRESS_BAR_SIZE == 0){ if (filesize > 0){ double pr = ((double)lfilesize) / filesize * 100; fprintf(stderr, "Thread %04d, Mapping %6.2f %% done (%10ld lines)...\\n", no, pr, lcounter); }else{ fprintf(stderr, "Thread %04d, Mapping %12ld bytes done (%10ld lines)...\\n", no, lfilesize, lcounter); } } if ( strcmp(filename, "-") ) if (ftell(F) >= map[no + 1]) break; } if ( strcmp(filename, "-") ) fclose(F); pclose(P); pthread_mutex_lock( &mutex1 ); total_lines = total_lines + lcounter; pthread_mutex_unlock( &mutex1 ); fprintf(stderr, "Thread %04d finished, %10ld lines read...\\n", no, lcounter); return 0; } void print_usage(const char *argv0){ printf("Micro Mapper v.%s\\n", VERSION); printf("Copyleft %s, Nikolay Mihaylov <nmmm@nmmm.nu>\\n", VERSION_DATE); printf("Build on %s, %s\\n", "Feb 9 2018", "18:46:06"); printf("\\n"); printf("Usage:\\n"); printf("\\t%s [input_filename] [mapper_program] [[num_threads]]\\n", argv0); printf("\\n"); printf("If you specify \\"-\\" as input filename, stdin will be used (without splitting).\\n"); printf("\\n"); printf("Build conf:\\n"); printf("\\t%-20s : %5d\\n", "Max threads", MAX_THREADS); printf("\\t%-20s : %5d\\n", "Default threads", DEF_THREADS); printf("\\t%-20s : %5d\\n", "Min file part", MIN_FILE_PART); printf("\\t%-20s : %5d\\n", "Max line size", MAX_BUFFER); printf("\\n"); }
0
#include <pthread.h> int global_variable_count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void* IncrementVariable(void *id) { int i; int threadID = (int)id; printf("Starting IncrementVariable(): thread %d\\n", threadID); for (i=0; i < 5; i++) { pthread_mutex_lock(&count_mutex); global_variable_count++; if (global_variable_count == 8) { pthread_cond_signal(&count_threshold_cv); printf("IncrementVariable(): thread %d, count = %d Limit reached.\\n", threadID, global_variable_count); } printf("IncrementVariable(): thread %d, incrementing count, count = %d, unlocking mutex\\n", threadID, global_variable_count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void* WatchVariable(void *id) { int threadID = (int)id; printf("Starting WatchVariable(): thread %d\\n", threadID); pthread_mutex_lock(&count_mutex); while (global_variable_count < 8) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("WatchVariable(): thread %d Condition signal received.\\n", threadID); global_variable_count += 1000; printf("WatchVariable(): thread %d count now = %d.\\n", threadID, global_variable_count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_create(&threads[0], &attr, WatchVariable, (void *)1); pthread_create(&threads[1], &attr, IncrementVariable, (void *)2); pthread_create(&threads[2], &attr, IncrementVariable, (void *)3); for (i=0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Done.\\n"); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); return 1; }
1
#include <pthread.h> struct queue { int *v; int head; int tail; int size; int maxsize; pthread_mutex_t mutex; }; struct queue *queue_create(int maxsize) { struct queue *q = malloc(sizeof(*q)); if (q != 0) { q->v = malloc(sizeof(int)*(maxsize+1)); if (q->v == 0) { free(q); return 0; } q->maxsize = maxsize; q->size = 0; q->head = maxsize + 1; q->tail = 0; pthread_mutex_init(&q->mutex, 0); } return q; } void lock_queue(struct queue *q) { pthread_mutex_lock(&q->mutex); } void unlock_queue(struct queue *q) { pthread_mutex_unlock(&q->mutex); } int queue_enqueue(struct queue *q, int value) { lock_queue(q); if(q->head == q->tail + 1) { fprintf(stderr,"queue: Queue overflow\\n"); unlock_queue(q); return-1; } q->v[q->tail++] = value; q->tail = q->tail % (q->maxsize+1); q->size++; unlock_queue(q); return 0; } int queue_dequeue(struct queue *q) { lock_queue(q); if (q->head % (q->maxsize + 1) == q->tail) { fprintf(stderr,"queue: Queue is empty\\n"); unlock_queue(q); return -1; } q->head = q->head % (q->maxsize+ 1); q->size--; unlock_queue(q); return q->v[q->head++]; } int queue_lookqueue(struct queue *q, int value) { lock_queue(q); if (q->head % (q->maxsize + 1) == q->tail) { fprintf(stderr,"queue: Queue is empty\\n"); unlock_queue(q); return -1; } int ptr = q->head; ptr = q->head % (q->maxsize+ 1); for (int i = 0; i < q->size; i++) { if ((q->v[ptr++]) == value) { unlock_queue(q); return value; } } unlock_queue(q); return -1; } int main() { struct queue *q; int i,val; q = queue_create(10); for(i = 1; i <= 11; i++) { queue_enqueue(q, i); } for(i = 1; i <= 11; i++) { printf("%d\\n", queue_lookqueue(q, i)); } for(i = 1; i <= 5; i++) { queue_dequeue(q); } for(i = 1; i <= 11; i++) { printf("%d\\n", queue_lookqueue(q, i)); } return 0; }
0
#include <pthread.h> void *func1 (void *arg); void *func2 (void *arg); void sig_handler (int signo); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int main () { pthread_t tid[2]; struct sigaction act; sigset_t newset; bzero (&act,sizeof (act)); bzero (&newset,sizeof (newset)); act.sa_flags = 0; act.sa_mask = newset; act.sa_handler = sig_handler; sigaction (SIGUSR1,&act,0); pthread_create (&tid[0],0,func1,(void *) 1); sleep (1); pthread_create (&tid[1],0,func2,(void *) 2); sleep (3); kill (getpid (),SIGUSR1); pthread_cond_signal (&cond); sleep (2); pthread_cond_signal (&cond); sleep (10); return 0; } void *func1 (void *arg) { int i = 0; i = (long) (arg); pthread_mutex_lock (&mutex); pthread_cond_wait (&cond,&mutex); return (void *) 0; } void *func2 (void *arg) { struct timespec timeval; clock_gettime (CLOCK_REALTIME,&timeval); timeval.tv_sec += 10; int i = 0; i = (long) (arg); pthread_mutex_lock (&mutex); pthread_cond_timedwait (&cond,&mutex,&timeval); pthread_mutex_unlock (&mutex); return (void *) 0; } void sig_handler (int signo) { printf ("Receive SIGUSR1,signo = %d\\n",signo); }
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); } struct Position { int min_x[10]; int min_y[10]; int max_x[10]; int max_y[10]; } positions; double start_time, end_time; int size, stripSize; int sums[10]; int mins[10]; int maxes[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] = rand()%99; } } for (i = 0; i < size; i++) { printf("[ "); for (j = 0; j < size; j++) { printf(" %d", matrix[i][j]); } printf(" ]\\n"); } 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, min, min_x, min_y, max, max_x, max_y, i, j, first, last; printf("worker %ld (pthread id %lu) has started\\n", myid, pthread_self()); first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); total = 0; min = 32767; max = INT_MIN; for (i = first; i <= last; i++) { for (j = 0; j < size; j++) { if(matrix[i][j] < min) { min = matrix[i][j]; min_x = j; min_y = i; } else if(matrix[i][j] > max) { max = matrix[i][j]; max_x = j; max_y = i; } total += matrix[i][j]; } } mins[myid] = min; maxes[myid] = max; positions.min_x[myid] = min_x; positions.min_y[myid] = min_y; positions.max_x[myid] = max_x; positions.max_y[myid] = max_y; sums[myid] = total; Barrier(); if (myid == 0) { total = 0; for (i = 0; i < numWorkers; i++) { total += sums[i]; } min = 32767; min_x = -1; min_y = -1; for (i = 0; i < numWorkers; i++) { if(mins[i] < min) { min = mins[i]; min_x = positions.min_x[i]; min_y = positions.min_y[i]; } } max = INT_MIN; for (i = 0; i < numWorkers; i++) { if(maxes[i] > max) { max = maxes[i]; max_x = positions.max_x[i]; max_y = positions.max_y[i]; } } end_time = read_timer(); printf("The total is %d\\n", total); printf("The min element is %d at (%d , %d)\\n", min, min_x, min_y); printf("The max element is %d at (%d , %d)\\n", max, max_x, max_y); printf("The execution time is %g sec\\n", end_time - start_time); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int numthreads; int increment; struct parameter { int id; int startInt; }; int id; struct node *next; }node; node *head; void insert(int id){ node *ptr,*temp; if(head == 0){ head = (node*)malloc(sizeof(node)); head->id = id; head->next = 0; }else{ ptr = head; while(ptr->next != 0){ ptr = ptr->next; } temp = (node*)malloc(sizeof(node)); temp->id = id; temp->next; ptr->next = temp; } } void traverse(){ node *ptr = head; while(ptr != 0){ printf("%d ",ptr->id); ptr = ptr->next; } printf("\\n"); free(ptr); } int sum(int a) { int sum = 0; int i; for (i = 0; i < increment; i++) { sum += a++; } return sum; } void* do_loop(void* data) { struct timeval tv1, tv2; gettimeofday(&tv1, 0); int rc = pthread_mutex_lock(&mutex); if (rc) { perror("pthread_mutex_lock"); pthread_exit(0); } struct parameter *pa = (struct parameter*) data; if(pa == 0){ }else{ int s = sum(pa -> startInt); if(s<=0|| s > 32767){ insert(pa->id); } printf("start interval : %d, thread id : %d, sum : %d\\n", pa -> startInt, pa -> id, s); pa -> startInt +=increment; pthread_mutex_unlock(&mutex); gettimeofday(&tv2, 0); long duration = 1000000 * (tv2.tv_sec - tv1.tv_sec) + (tv2.tv_usec - tv1.tv_usec); printf("run duration : %ld microseconds\\n", duration); pthread_exit(0); free(pa); } } int isDigit(char *str){ int i=0; int rt = 1; while(str[i]){ if(str[i] < 48 || str[i] > 57){ rt = 0; break; } i++; } return rt; } int main(int argc, char **argv) { if(argc < 3){ printf("System expecting more number of inputs.\\n"); printf("Please enter num_of_threads and interval values as command line arguments!!!\\n"); }else if(isDigit(argv[1])==0 || isDigit(argv[2])==0){ printf("System expecting some number input!!!!\\n"); }else{ struct timeval tv1, tv2; gettimeofday(&tv1, 0); const int firstint = 0; numthreads = atoi(argv[1]); increment = atoi(argv[2]); struct parameter new; new.startInt = firstint; pthread_t p_thread; int j; for (j = 0; j < numthreads; j++) { new.id = j; pthread_create(&p_thread, 0, do_loop, (void*)&new); pthread_join(p_thread, 0); } gettimeofday(&tv2, 0); long duration = 1000000 * (tv2.tv_sec - tv1.tv_sec) + (tv2.tv_usec - tv1.tv_usec); printf("Program run duration was : %ld microseconds\\n", duration); if(head != 0) printf("\\nList of threads not supported::\\n"); traverse(); } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t sinalAcordaBarbeiro = PTHREAD_COND_INITIALIZER; pthread_cond_t chamaCliente = PTHREAD_COND_INITIALIZER; int costumers=0; int ocupado=0; int temCadeiraVazia(){ if (costumers<5){ return 1; } return 0; } void *barbeiro(void *args){ while(1){ pthread_mutex_lock(&mutex); ocupado=0; if(costumers==0){ printf("\\nB:Vou dormir,nao tem cliente!Clientes:%d\\n",costumers); pthread_cond_wait(&sinalAcordaBarbeiro,&mutex); } printf("\\nB:Chamei um cliente.Clientes:%d\\n",costumers); costumers-=1; ocupado=1; pthread_cond_signal(&chamaCliente); pthread_mutex_unlock(&mutex); printf("\\nB:Estou cortando o cabelo de um cliente.Clientes:%d\\n",costumers); } } void *cliente(void *args){ while(1){ pthread_mutex_lock(&mutex); if(temCadeiraVazia){ costumers+=1; printf("\\nC:Chegou um consumidor.Clientes:%d\\n",costumers); if(costumers==1){ pthread_cond_signal(&sinalAcordaBarbeiro); } if(ocupado==1){ pthread_cond_wait(&chamaCliente,&mutex); } pthread_mutex_unlock(&mutex); printf("\\nC:Tendo o cabelo cortado\\n"); sleep(10); } else{ pthread_mutex_unlock(&mutex); } } } int main(){ pthread_t barbeiroT; pthread_t consumidor; pthread_create(&barbeiroT,0,&barbeiro,0); pthread_create(&consumidor,0,&cliente,0); do{ }while(1); }
0
#include <pthread.h> char* shm; pthread_mutex_t* mutex; char* attach_shm() { int fd = shm_open("/share_memory", O_RDWR|O_CREAT|O_EXCL, 0777); if(fd > 0) { ftruncate(fd, 4096); } else { fd = shm_open("/share_memory", O_RDWR, 0777); } printf("fd is %d\\n", fd); void* ptr = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(ptr == MAP_FAILED) { printf("map error"); } return ptr; } int main() { shm = attach_shm(); printf("%s\\n", (char*)shm); mutex = (pthread_mutex_t*)(shm+10); pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mutex, &mutexattr); pthread_mutex_lock(mutex); printf("get mutex\\n"); getchar(); printf("ready to release mutex\\n"); pthread_mutex_unlock(mutex); printf("release mutex done\\n"); }
1
#include <pthread.h> int queue, max; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * producer(void *x) { int rnd; while (1) { pthread_mutex_lock(&mutex); while (queue == max) { (void) printf("Queue full, producer sleeping.\\n"); pthread_cond_wait(&cond, &mutex); } rnd = random() % 2; if (queue == 0 && rnd == 1) pthread_cond_signal(&cond); queue = queue + rnd; pthread_mutex_unlock(&mutex); poll(0, 0, 95); } } void * consumer(void *x) { int rnd; while (1) { pthread_mutex_lock(&mutex); while (queue == 0) { pthread_cond_wait(&cond, &mutex); } rnd = random() % 2; if (queue == max && rnd == 1) { (void) printf("Queue no longer full, signalling " "producer.\\n"); pthread_cond_signal(&cond); } queue = queue - rnd; pthread_mutex_unlock(&mutex); poll(0, 0, 100); } } int main(int argc, char **argv) { int i; pthread_t t_prod, t_cons; if (argc == 2) max = atoi(argv[1]); else max = 10; srandom(time(0)); pthread_create(&t_prod, 0, producer, 0); pthread_create(&t_cons, 0, consumer, 0); while (1) { pthread_mutex_lock(&mutex); printf(" |"); for (i = 0; i < queue; ++i) putchar('.'); for (i = queue; i < max; ++i) putchar(' '); printf("|\\n"); pthread_mutex_unlock(&mutex); poll(0, 0, 85); } return (0); }
0
#include <pthread.h> struct async_list { void **data; uint64_t count; uint64_t size; pthread_mutex_t lock; }; struct async_list * async_list_new (void) { struct async_list *l = calloc (1, sizeof (struct async_list)); if (0 == l) return 0; pthread_mutex_init (&l->lock, 0); return l; } void async_list_add (struct async_list *l, void *item) { assert (l); pthread_mutex_lock (&l->lock); if (l->size <= l->count) { l->size = l->size ? l->size * 2 : 2; assert (l->data = realloc (l->data, sizeof (void *) * l->size)); } l->data[l->count++] = item; pthread_mutex_unlock (&l->lock); } void * async_list_get (struct async_list *l, uint64_t i) { void *p; assert (l); pthread_mutex_lock (&l->lock); assert (l->data); assert (l->count <= i); p = l->data[i]; pthread_mutex_unlock (&l->lock); return p; } uint64_t async_list_count (struct async_list *l) { uint64_t p; assert (l); pthread_mutex_lock (&l->lock); p = l->count; pthread_mutex_unlock (&l->lock); return p; } void async_list_free (struct async_list *l) { pthread_mutex_destroy (&l->lock); free (l->data); free (l); }
1
#include <pthread.h> pthread_mutex_t pingmtx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t pongmtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t pingcv = PTHREAD_COND_INITIALIZER; pthread_cond_t pongcv = PTHREAD_COND_INITIALIZER; int minprio; int maxprio; int nrmlprio; int specprio; int main( int, char **); void Ping(int *); void Pong(int *); static void SchedReport(char *,char *); int main( int argc, char **argv) { pthread_attr_t attr; pthread_t ping; pthread_t pong; int pingresult; int pongresult; struct sched_param mainsp; minprio = sched_get_priority_min(SCHED_FIFO); maxprio = sched_get_priority_max(SCHED_FIFO); nrmlprio = (minprio + maxprio)/2; specprio = nrmlprio + 1; mainsp.sched_priority = nrmlprio; pthread_setschedparam(pthread_self(),SCHED_FIFO,&mainsp); pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr,SCHED_FIFO); pthread_attr_setschedparam(&attr,&mainsp); pthread_create(&ping,&attr,(void *) Ping,&pingresult); pthread_create(&pong,&attr,(void *) Pong,&pongresult); sched_yield(); pthread_cond_signal(&pingcv); pthread_join(ping,0); pthread_join(pong,0); printf("ping result=%d\\n","\\e[m",pingresult); printf("pong result=%d\\n","\\e[m",pongresult); } void Ping(int *result) { int loop; int i; double x; struct sched_param nrmlsp; struct sched_param specsp; nrmlsp.sched_priority= nrmlprio; specsp.sched_priority= specprio; for(loop= 0; loop < 100; ++loop) { pthread_setschedparam(pthread_self(),SCHED_FIFO,&specsp); SchedReport("\\e[32m","ping"); pthread_cond_signal(&pongcv); pthread_mutex_lock(&pingmtx); pthread_cond_wait(&pingcv,&pingmtx); pthread_mutex_unlock(&pingmtx); pthread_setschedparam(pthread_self(),SCHED_FIFO,&nrmlsp); sched_yield(); for(i= 0, x= 0.; i < 10000; ++i) { x+= sin((double) i*M_PI/10000); } } printf("%sping now trying to exit\\n","\\e[33m"); fflush(stdout); pthread_cond_signal(&pongcv); *result= (int) x; sched_yield(); pthread_exit(0); } void Pong(int *result) { int loop; int i; double x; struct sched_param nrmlsp; struct sched_param specsp; nrmlsp.sched_priority= nrmlprio; specsp.sched_priority= specprio; for(loop= 0; loop < 100; ++loop) { pthread_setschedparam(pthread_self(),SCHED_FIFO,&specsp); SchedReport("\\e[31m","pong"); pthread_cond_signal(&pingcv); pthread_mutex_lock(&pongmtx); pthread_cond_wait(&pongcv,&pongmtx); pthread_mutex_unlock(&pongmtx); pthread_setschedparam(pthread_self(),SCHED_FIFO,&nrmlsp); sched_yield(); for(i= 0, x= 0.; i < 10000; ++i) { x+= sin((double) i*M_PI/10000); } } printf("%spong now trying to exit\\n","\\e[33m"); fflush(stdout); pthread_cond_signal(&pingcv); *result= (int) x; sched_yield(); pthread_exit(0); } static void SchedReport(char *escseq,char *thrdname) { struct sched_param sp; int policy; pthread_getschedparam(pthread_self(),&policy,&sp); printf("%s%s : policy=%d<%s> priority=%d\\n", escseq,thrdname, policy, (policy == SCHED_RR)? "rr" : (policy == SCHED_FIFO)? "fifo" : (policy == SCHED_OTHER)? "other" : "???", sp.sched_priority); }
0
#include <pthread.h> pthread_mutex_t lock; FILE *fptr; void *reader1(void *threadid) { while(1) { pthread_mutex_lock(&lock); int temp = *(int *)threadid; printf("Thread no: %d ",temp); printf("Lock accquired by reader 1\\n"); int i=0; char ch,result[100]; ch = fgetc(fptr); if (ch == EOF) { printf("No more strings left \\n"); break; } printf("\\n\\n"); i=0; while(ch!='\\n') { result[i++]=ch; ch = fgetc(fptr); } result[i++]='\\0'; puts(result); printf("\\n"); pthread_mutex_unlock(&lock); printf("Lock released by reader 1\\n"); } pthread_exit(0); } void *reader2(void *threadid) { while(1) { pthread_mutex_lock(&lock); int temp = *(int *)threadid; printf("Thread no: %d ",temp); printf("Lock accquired by reader 2\\n"); int i=0; char ch,result[100]; ch = fgetc(fptr); if (ch == EOF) { printf("No more strings left \\n"); break; } printf("\\n\\n"); i=0; while(ch!='\\n') { result[i++]=ch; ch = fgetc(fptr); } result[i++]='\\0'; puts(result); printf("\\n"); pthread_mutex_unlock(&lock); printf("Lock released by reader 2\\n"); } pthread_exit(0); } void main() { pthread_t thread1[2]; fptr = fopen("test.txt","r"); int rc,temp1=1; rc = pthread_create(&thread1[0],0,reader1,(void *)&temp1); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } int temp2 = 2; rc = pthread_create(&thread1[1],0,reader2,(void *)&temp2); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } sleep(1); fclose(fptr); return; }
1
#include <pthread.h> struct SysThread { pthread_t thread; }; struct SysMutex { pthread_mutex_t mutex; }; struct SysThread *Sys_Thread_CreateThread(void (*entrypoint)(void *), void *argument) { struct SysThread *thread; int r; thread = malloc(sizeof(*thread)); if (thread) { r = pthread_create(&thread->thread, 0, entrypoint, argument); if (r == 0) { return thread; } free(thread); } return 0; } void Sys_Thread_DeleteThread(struct SysThread *thread) { pthread_join(thread->thread, 0); free(thread); } int Sys_Thread_SetThreadPriority(struct SysThread *thread, enum SysThreadPriority priority) { fprintf(stderr, "%s: stub\\n", __func__); return 0; } struct SysMutex *Sys_Thread_CreateMutex(void) { struct SysMutex *mutex; int r; mutex = malloc(sizeof(*mutex)); if (mutex) { r = pthread_mutex_init(&mutex->mutex, 0); if (r == 0) { return mutex; } free(mutex); } return 0; } void Sys_Thread_DeleteMutex(struct SysMutex *mutex) { pthread_mutex_destroy(&mutex->mutex); free(mutex); } void Sys_Thread_LockMutex(struct SysMutex *mutex) { pthread_mutex_lock(&mutex->mutex); } void Sys_Thread_UnlockMutex(struct SysMutex *mutex) { pthread_mutex_unlock(&mutex->mutex); }
0
#include <pthread.h> pthread_mutex_t marker_mutex; int MARKER; int maxx; int maxy; int color_lum_min = 220; int color_lum_max = 255; int color_cb_min = 0; int color_cb_max = 255; int color_cr_min = 0; int color_cr_max = 255; int blob_threshold = 2500; static struct video_listener* helipad_listener; struct results helipad_marker; struct results_color color_marker; int modify_image_color = FALSE; int modify_image_helipad = TRUE; int squares = 4; int med = 0; int bin_thresh = 230; struct image_t *helipad_tracking_func(struct image_t* img); struct image_t *helipad_tracking_func(struct image_t* img) { color_marker = locate_blob(img, color_lum_min, color_lum_max, color_cb_min, color_cb_max, color_cr_min, color_cr_max, blob_threshold); if ((modify_image_color) && (color_marker.MARKER)) { int ti = color_marker.maxy - 50; int bi = color_marker.maxy + 50; struct point_t t = {color_marker.maxx, ti}, b = {color_marker.maxx, bi}; int li = color_marker.maxx - 50; int ri = color_marker.maxx + 50; struct point_t l = {li, color_marker.maxy}, r = {ri, color_marker.maxy}; image_draw_line(img, &t, &b); image_draw_line(img, &l, &r); } if (sonar_bebop.distance < 1.2) { squares = 1; } else { squares = 2; } if (sonar_bebop.distance < 1.6) { bin_thresh = 230; } else { bin_thresh = 220; } if (img->type == IMAGE_YUV422) { helipad_marker = opencv_imav_landing((char*) img->buf, img->w, img->h, squares, bin_thresh, modify_image_helipad); } else { helipad_marker.MARKER = 0; } pthread_mutex_lock(&marker_mutex); if (helipad_marker.MARKER) { MARKER = helipad_marker.MARKER; maxx = helipad_marker.maxx; maxy = helipad_marker.maxy; } else if ((color_marker.MARKER) && (sonar_bebop.distance > 1)) { } else { MARKER = FALSE; } pthread_mutex_unlock(&marker_mutex); return 0; } void helipad_init(void) { helipad_listener = cv_add_to_device_async(&HELIPAD_CAMERA, helipad_tracking_func, 5); helipad_listener->maximum_fps = 10; } int helipad_periodic(void) { return 0; } int start_helipad(void) { helipad_listener->active=1; return 0; } int stop_helipad(void) { helipad_listener->active=0; return 0; }
1
#include <pthread.h> pthread_t thread1, thread2; static pthread_mutex_t verrou1, verrou2; int var1, var2, var3; void *lire(void *nom_du_thread) { pthread_mutex_lock(&verrou1); printf("lire variable 1 = %d\\n",var1); printf("lire variable 2 = %d\\n",var2); printf("lire variable 3 = %d\\n",var3); pthread_exit(0); } void *ecrire(void *nom_du_thread) { pthread_mutex_lock(&verrou2); var1=20; var2=1; var3=16; printf("ecriture %d dans variable 1 \\n",var1); printf("ecriture %d dans variable 2 \\n",var2); printf("ecriture %d dans variable 3 \\n",var3); sleep(1); pthread_exit(0); } int main() { pthread_mutex_init(&verrou1,0); pthread_mutex_init(&verrou2,0); pthread_mutex_lock(&verrou1); pthread_mutex_lock(&verrou2); pthread_create(&thread1,0,lire,0); pthread_create(&thread2,0,ecrire,0); pthread_mutex_unlock(&verrou2); pthread_join(thread2,0); pthread_mutex_unlock(&verrou1); pthread_join(thread1,0); }
0
#include <pthread.h> pthread_mutex_t asientos_mutex[5 * 2]; int asientos[5 * 2 * 2]; void *cliente(void *arg) { int id = *(int *) arg; while (1) { int complejo; int sala; int asiento; int pos; printf("%d - .........\\n", id); usleep(rand() % 500000); complejo = rand() % 5; printf("%d Selecciono el complejo %d\\n", id, complejo); usleep(rand() % 500000); sala = rand() % 2; printf("%d Selecciono la sala %d\\n", id, sala); usleep(rand() % 500000); asiento = rand() % 2; printf("%d Selecciono el asiento %d\\n", id, asiento); pos = (complejo * 2 + sala) * 2 + asiento; pthread_mutex_lock(&asientos_mutex[pos]); int temp = asientos[pos]; if (!temp) { asientos[pos] = 1; printf("%d: Asiento %d lo ocupe\\n", id, asiento); pthread_mutex_unlock(&asientos_mutex[pos]); break; } else { printf("%d Asiento %d ocupado\\n", id, asiento); pthread_mutex_unlock(&asientos_mutex[pos]); } } } int main() { srand(time(0)); int i; for (i = 0; i < 5 * 2 * 2; ++i) { pthread_mutex_init(&asientos_mutex[i], 0); asientos[i] = 0; } pthread_t clientes_t[5]; int ids[5]; for (i = 0; i < 5; ++i) { ids[i] = i; pthread_create(&clientes_t[i], 0, cliente, &ids[i]); } for (i = 0; i < 5; ++i) { pthread_join(clientes_t[i], 0); } pthread_exit(0); }
1
#include <pthread.h> void mutex_set_tab(pthread_mutex_t *mutex, int *ptr[], int val[], int size) { int i; i = 0; pthread_mutex_lock(mutex); while (i < size) { *ptr[i] = val[i]; i++; } pthread_mutex_unlock(mutex); return ; }
0
#include <pthread.h> pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t thread_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t thread_cond2 = PTHREAD_COND_INITIALIZER; struct com_data { int a; int b; }; struct com_data mydata; void *do_write(void *data) { mydata.a = 0; mydata.b = 0; while(1) { pthread_mutex_lock(&mutex_lock); mydata.a = rand() % 6000; mydata.b = rand() % 6000; pthread_cond_signal(&thread_cond); pthread_cond_wait(&thread_cond2, &mutex_lock); pthread_mutex_unlock(&mutex_lock); } } void *do_read(void *data) { while(1) { pthread_mutex_lock(&mutex_lock); pthread_cond_wait(&thread_cond, &mutex_lock); pthread_cond_signal(&thread_cond2); printf("%4d + %4d = %4d\\n", mydata.a, mydata.b, mydata.a + mydata.b); pthread_mutex_unlock(&mutex_lock); } } int main() { pthread_t p_thread[2]; int thr_id; int status; int a = 1; int b = 2; thr_id = pthread_create(&p_thread[0], 0, do_write, (void *)&a); thr_id = pthread_create(&p_thread[1], 0, do_read, (void *)&b); pthread_join(p_thread[0], (void **) status); pthread_join(p_thread[1], (void **) status); return 0; }
1
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; static pthread_cond_t wait = PTHREAD_COND_INITIALIZER; static void* _thread1(void *__u ) { printf("1: obtaining mutex\\n"); pthread_mutex_lock(&lock); printf("1: waiting on condition variable\\n"); pthread_cond_wait(&wait, &lock); printf("1: releasing mutex\\n"); pthread_mutex_unlock(&lock); printf("1: exiting\\n"); return 0; } static void* _thread2(void *__u ) { int cnt = 2; while(cnt--) { printf("2: obtaining mutex\\n"); pthread_mutex_lock(&lock); printf("2: signaling\\n"); pthread_cond_signal(&wait); printf("2: releasing mutex\\n"); pthread_mutex_unlock(&lock); } printf("2: exiting\\n"); return 0; } static const thread_func thread_routines[] = { &_thread1, &_thread2, }; int main(void) { pthread_t t[2]; int nn; int count = (int)(sizeof t/sizeof t[0]); for (nn = 0; nn < count; nn++) { printf("main: creating thread %d\\n", nn+1); if (pthread_create( &t[nn], 0, thread_routines[nn], 0) < 0) { printf("main: could not create thread %d: %s\\n", nn+1, strerror(errno)); return -2; } } for (nn = 0; nn < count; nn++) { printf("main: joining thread %d\\n", nn+1); if (pthread_join(t[nn], 0)) { printf("main: could not join thread %d: %s\\n", nn+1, strerror(errno)); return -2; } } return 0; }
0
#include <pthread.h> extern const unsigned short g_server_port; pthread_t g_listener_thread = 0; pthread_mutex_t g_client_handle_mutex = PTHREAD_MUTEX_INITIALIZER; static void *agt_listener_thread(void *params) { struct sockaddr_in local; struct sockaddr remote; int sock, con, remote_len; sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock <= 0) { logger("Open socket error"); return -1; } local.sin_family = AF_INET; local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(g_server_port); if( 0 != bind(sock, (const struct sockaddr *)&local, sizeof(local)) ) { logger("Bind socket error"); return -1; } if( 0 != listen(sock, 10) ) { logger("Listen socket error"); } while(1) { con = 0; memset(&remote, 0x00, sizeof(remote)); if(0 < (con = accept(sock, &remote, &remote_len)) ) { agt_client_handle(con); } } pthread_exit(); } void *agt_client_handler_thread(void *params){ db_init(); while(1){ } db_close(); pthread_exit(); } int agt_listener_start() { int status = pthread_create(&g_listener_thread, (pthread_attr_t*)0, agt_listener_thread, (void*)0); if( 0!= status) { logger("pthread_create create socket listener error: %d", status); } else { logger("Connection Listener thread has been started"); } return status; } int agt_client_handle(int client){ int identifier = client, status; pthread_t handler_thread; pthread_mutex_lock(&g_client_handle_mutex); status = pthread_create(&handler_thread, (pthread_attr_t*)0, agt_client_handler_thread, (void*)&identifier); if( 0!= status) { logger("pthread_create create socket listener error: %d", status); } else { logger("Connection Listener thread has been started"); } pthread_mutex_unlock(&g_client_handle_mutex); return status; } int agt_man_main() { agt_listener_start(); return 0; }
1
#include <pthread.h> int a = 0; int b = 0; pthread_mutex_t mutex_a; pthread_mutex_t mutex_b; void *another(void *arg) { pthread_mutex_lock(&mutex_b); printf("in child thread, got mutex b, waiting for mutex a\\n"); sleep(5); ++b; pthread_mutex_lock(&mutex_a); b += a++; pthread_mutex_unlock(&mutex_a); pthread_mutex_unlock(&mutex_b); pthread_exit(0); return 0; } int main(int argc, char *argv[]) { pthread_t thid; pthread_mutex_init(&mutex_a, 0); pthread_mutex_init(&mutex_b, 0); pthread_create(&thid, 0, another, 0); pthread_mutex_lock(&mutex_a); printf("in parent thread, got mutex a, waiting for mutex b\\n"); sleep(5); ++a; pthread_mutex_lock(&mutex_b); a += b++; pthread_mutex_unlock(&mutex_b); pthread_mutex_unlock(&mutex_a); pthread_join(thid, 0); pthread_mutex_destroy(&mutex_a); pthread_mutex_destroy(&mutex_b); return 0; }
0
#include <pthread.h> char queue [5] ; int front = 0 , rear = 0 ; int items = 0 ; int done = 1 ; pthread_mutex_t mutex ; pthread_cond_t item_available ; pthread_cond_t space_available ; void * p_thread() ; void * c_thread() ; int main(int argc, char *argv[]) { pthread_t producer , consumer; pthread_cond_init (&item_available, 0) ; pthread_cond_init (&space_available, 0) ; pthread_mutex_init (&mutex, 0) ; if( pthread_create ( &producer , 0, p_thread, 0)) { fprintf(stderr, "Error creating producer thread\\n"); return 1; } if( pthread_create ( &consumer , 0, c_thread, 0)) { fprintf(stderr, "Error creating consumer thread\\n"); return 1; } if ( pthread_join ( producer , 0 ) ) { fprintf(stderr, "Error joining thread\\n"); return 2; } if ( pthread_join ( consumer , 0 ) ) { fprintf(stderr, "Error joining consumer\\n"); return 2; } return 0; } void * p_thread() { FILE *fp = fopen("message.txt","r"); char c ; c = getc(fp); while (c != EOF) { sleep(1); pthread_mutex_lock (&mutex) ; printf (" front<%d> rear<%d> items <%d>\\n", front , rear , items ) ; while ( items >= 5 ) pthread_cond_wait ( &space_available , &mutex ) ; printf (" front<%d> rear<%d> items <%d>\\n", front , rear , items ) ; queue [front] = c ; front ++ ; if(front==5) front = 0 ; items ++ ; printf (" character write to queue: <%c>\\n" , c ) ; printf (" wake up a consumer \\n" ) ; pthread_cond_signal(&item_available); pthread_mutex_unlock (&mutex) ; sleep (1); c = getc(fp); } pthread_mutex_lock (&mutex) ; done = 0 ; pthread_cond_signal(&item_available); pthread_mutex_unlock (&mutex) ; fclose (fp); pthread_exit (0); } void * c_thread() { FILE* output = fopen ("message_result.txt" , "w") ; while ( done != 0 ) { pthread_mutex_lock (&mutex) ; printf ("front<%d> rear<%d> items <%d>\\n", front , rear , items ) ; while ( items <= 0 && done!= 0 ) pthread_cond_wait ( &item_available , &mutex ) ; printf ("front<%d> rear<%d> items <%d>\\n", front , rear , items ) ; char c = queue [rear] ; rear ++ ; if (rear==5) rear = 0 ; items -- ; printf ("character read from queue: <%c>\\n" , c ) ; printf ("wake up a producer \\n" ) ; fprintf(output,"%c",c) ; pthread_cond_signal(&space_available); pthread_mutex_unlock (&mutex) ; } fclose (output) ; pthread_exit (0); }
1
#include <pthread.h> int num_philosophers; pthread_mutex_t stdout_mutex; pthread_mutex_t random_mutex; pthread_mutex_t *fork_mutex; pthread_t *philosophers; void * xmalloc (size_t n) { void *p = malloc (n); if (! p) { fprintf (stderr, "out of memory\\n"); exit (2); } return p; } void shared_printf (char *format, ...) { va_list ap; __builtin_va_start((ap)); pthread_mutex_lock (&stdout_mutex); vprintf (format, ap); pthread_mutex_unlock (&stdout_mutex); ; } int shared_random () { int result; pthread_mutex_lock (&random_mutex); result = rand (); pthread_mutex_unlock (&random_mutex); return result; } void my_usleep (long usecs) { struct timeval timeout; timeout.tv_sec = usecs / 1000000; timeout.tv_usec = usecs % 1000000; select (0, 0, 0, 0, &timeout); } void random_delay () { my_usleep ((shared_random () % 2000) * 100); } void print_philosopher (int n, char left, char right) { int i; shared_printf ("%*s%c %d %c\\n", (n * 4) + 2, "", left, n, right); } void * philosopher (void *data) { int n = * (int *) data; print_philosopher (n, '_', '_'); if (n == num_philosophers - 1) for (;;) { pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]); print_philosopher (n, '_', '!'); random_delay (); pthread_mutex_lock (&fork_mutex[n]); print_philosopher (n, '!', '!'); random_delay (); print_philosopher (n, '_', '_'); pthread_mutex_unlock (&fork_mutex[n]); pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]); random_delay (); } else for (;;) { pthread_mutex_lock (&fork_mutex[n]); print_philosopher (n, '!', '_'); random_delay (); pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]); print_philosopher (n, '!', '!'); random_delay (); print_philosopher (n, '_', '_'); pthread_mutex_unlock (&fork_mutex[n]); pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]); random_delay (); } return (void *) 0; } int main (int argc, char **argv) { num_philosophers = 5; { pthread_mutexattr_t ma; int i; pthread_mutexattr_init (&ma); pthread_mutex_init (&stdout_mutex, &ma); pthread_mutex_init (&random_mutex, &ma); fork_mutex = xmalloc (num_philosophers * sizeof (fork_mutex[0])); for (i = 0; i < num_philosophers; i++) pthread_mutex_init (&fork_mutex[i], &ma); pthread_mutexattr_destroy (&ma); } { int i; int *numbers = xmalloc (num_philosophers * sizeof (*numbers)); pthread_attr_t ta; philosophers = xmalloc (num_philosophers * sizeof (*philosophers)); pthread_attr_init (&ta); for (i = 0; i < num_philosophers; i++) { numbers[i] = i; pthread_create (&philosophers[i], &ta, philosopher, &numbers[i]); } pthread_attr_destroy (&ta); } sleep (1000000); for (;;) sleep (1000000); return 0; }
0
#include <pthread.h> int x = 0; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void *thread_func (void * arg) { while(1) { pthread_mutex_lock(&mut); x=5; x+=10; printf("x is %d in thread %lu\\n",x,pthread_self()); sleep(1); pthread_mutex_unlock(&mut); } } int main() { pthread_t tid1; pthread_t tid2; pthread_create(&tid1, 0, &thread_func, 0); pthread_create(&tid2, 0, &thread_func, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); }
1
#include <pthread.h> struct stack { char x[PTHREAD_STACK_MIN]; }; static pthread_mutex_t mutex[(503)]; static int data[(503)]; static struct stack stacks[(503)]; static void* thread(void *num) { int l = (int)num; int r = (l+1) % (503); int token; while(1) { pthread_mutex_lock(mutex + l); token = data[l]; if (token) { data[r] = token - 1; pthread_mutex_unlock(mutex + r); } else { printf("%i\\n", l+1); exit(0); } } } int main(int argc, char **argv) { int i; pthread_t cthread; pthread_attr_t stack_attr; if (argc != 2) exit(255); data[0] = atoi(argv[1]); pthread_attr_init(&stack_attr); for (i = 0; i < (503); i++) { pthread_mutex_init(mutex + i, 0); pthread_mutex_lock(mutex + i); pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack)); pthread_create(&cthread, &stack_attr, thread, (void*)i); } pthread_mutex_unlock(mutex + 0); pthread_join(cthread, 0); return 0; }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; int numthrds; } DOTDATA; DOTDATA dotstr; pthread_t callThd[2]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len, numthrds, myid; long mythrd; double mysum, *x, *y; mythrd = (long)arg; MPI_Comm_rank (MPI_COMM_WORLD, &myid); numthrds = dotstr.numthrds; len = dotstr.veclen; start = myid*numthrds*len + mythrd*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); printf("Task %d thread %ld adding partial sum of %f to node sum of %f\\n", myid, mythrd, mysum, dotstr.sum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit((void*)0); } int main(int argc, char* argv[]) { int len=5, myid, numprocs; long i; int nump1, numthrds; double *a, *b; double nodesum, allsum; void *status; pthread_attr_t attr; MPI_Init (&argc, &argv); MPI_Comm_size (MPI_COMM_WORLD, &numprocs); MPI_Comm_rank (MPI_COMM_WORLD, &myid); numthrds=2; a = (double*) malloc (numprocs*numthrds*len*sizeof(double)); b = (double*) malloc (numprocs*numthrds*len*sizeof(double)); for (i=0; i<len*numprocs*numthrds; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = len; dotstr.a = a; dotstr.b = b; dotstr.sum=0; dotstr.numthrds=2; pthread_attr_init(&attr ); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init (&mutexsum, 0); for(i=0;i<numthrds;i++) { pthread_create( &callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr ); for(i=0;i<numthrds;i++) { pthread_join( callThd[i], &status); } nodesum = dotstr.sum; printf("Task %d node sum is %f\\n",myid, nodesum); MPI_Reduce (&nodesum, &allsum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (myid == 0) printf ("Done. MPI with threads version: sum = %f \\n", allsum); MPI_Finalize(); free (a); free (b); pthread_mutex_destroy(&mutexsum); exit (0); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv_th(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=') ) { strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
0
#include <pthread.h> pthread_mutex_t g_TrackMutex; int isMutexInit = 0; int isLogged = 0; void track(const char* fun_name, int fun_line, const char *format,... ) { va_list args; struct tm *pstTm; FILE *pFILE = 0;; long lClock; char cMsg[256] = {'\\0'}; char cString[128] = {'\\0'}; if(0 == isLogged) return; if(0 == isMutexInit) { isMutexInit = 1; pthread_mutex_init(&g_TrackMutex,0); } pthread_mutex_lock(&g_TrackMutex); lClock = time((long *)0); pstTm = localtime( &lClock ); sprintf( cMsg, "%04d-%02d-%02d %02d:%02d:%02d %s(%d): ", pstTm->tm_year+1900, pstTm->tm_mon+1, pstTm->tm_mday, pstTm->tm_hour, pstTm->tm_min, pstTm->tm_sec, fun_name, fun_line); const char* FILENAME_PATH_DEFAULT = "/tmp/userv.log"; sprintf( cString,FILENAME_PATH_DEFAULT); pFILE = fopen( cString, "a" ); if( pFILE == 0 ) { pthread_mutex_unlock (&g_TrackMutex); return; } fputs( cMsg, pFILE ); __builtin_va_start((args)); vfprintf(pFILE ,format, args ) ; ; fputs( "\\n", pFILE ); fclose( pFILE ); pthread_mutex_unlock (&g_TrackMutex); }
1
#include <pthread.h> const char *names[5] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" }; pthread_mutex_t forks[5]; const char *topic[5] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; __builtin_va_start((ap)); pthread_mutex_lock(&screen); printf("\\033[%d;%dH", y + 1, x), vprintf(fmt, ap); printf("\\033[%d;%dH", 5 + 1, 1), fflush(stdout); pthread_mutex_unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % 5; print(id, 12, "\\033[K"); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { pthread_mutex_lock(forks + f[i]); if (!i) print(id, 12, "\\033[K"); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { print(id, 12, "\\033[K"); sprintf(buf, "..oO (%s)", topic[t = rand() % 5]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[5]; pthread_t tid[5]; for (i = 0; i < 5; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < 5; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; 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(&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->fcount--; 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> static int next_free_id = 1; struct poll_record *head = 0; pthread_mutex_t list_mutex; char *lock_owner = 0; void pr_init() { pthread_mutexattr_t attr; if (pthread_mutexattr_init(&attr)) perror("ERROR => Error attempting to init mutexattr. The error was:"); if (pthread_mutex_init(&list_mutex, &attr)) perror("ERROR => Error attempting to init mutex. The error was"); if (pthread_mutexattr_destroy(&attr)) perror("ERROR => Error attempting to destroy mutexattr. The error was"); } void pr_lock(char *new_lock_owner) { assert(new_lock_owner); pthread_mutex_lock(&list_mutex); lock_owner = new_lock_owner; } void pr_unlock() { assert(lock_owner); lock_owner = 0; pthread_mutex_unlock(&list_mutex); } struct poll_record *pr_get_head() { assert(lock_owner); return head; } void pr_insert(struct poll_record *record) { assert(record); assert(lock_owner); if (record->id == 0) record->id = next_free_id++; if (record->next_poll_time == 0) { record->next_poll_time = ceilf((float)get_time_in_ms() / 1000) * 1000; } if (!head) { head = record; record->prev = record->next = 0; return; } struct poll_record *current = (struct poll_record*)head; struct poll_record *last = 0; while (current && current->next_poll_time < record->next_poll_time) { last = current; current = current->next; } if (last == 0) { record->prev = 0; record->next = current; head = record; current->prev = record; } else if (current == 0) { last->next = record; record->prev = last; record->next = 0; } else { record->prev = last; record->next = current; last->next = record; current->prev = record; } } void pr_remove(struct poll_record *record) { assert(record); assert(lock_owner); if (head == record) { head = record->next; if (record->next) record->next->prev = 0; } else { if (!record->prev) { fprintf(stderr, "record isn't in list."); return; } record->prev->next = record->next; if (record->next) record->next->prev = record->prev; } record->next = 0; record->prev = 0; } struct poll_record *pr_find(int id) { assert(lock_owner); struct poll_record *current = (struct poll_record *)head; while (current) { if (current->id == id) return current; current = current->next; } return 0; } void pr_clear_and_free_all() { assert(lock_owner); struct poll_record *current, *next; current = head; while (current) { next = current->next; free(current); current = next; } head = 0; }
0
#include <pthread.h> int smoother_init(struct smoother_t *smoother) { int rc; smoother->pos = 0; smoother->ready = 0; rc = pthread_mutex_init(&(smoother->mtx), 0); return rc; } void smoother_push(struct smoother_t *smoother, float timestamp, float value) { pthread_mutex_lock(&(smoother->mtx)); if (smoother->pos == RING_BUFFER_SIZE) { printf("smoother is ready\\n"); smoother->ready = 1; smoother->pos = 0; } struct measurement_t *measurement = &(smoother->ring_buffer[smoother->pos]); measurement->timestamp = timestamp; measurement->value = value; smoother->pos += 1; pthread_mutex_unlock(&(smoother->mtx)); } void smoother_average__(struct smoother_t *smoother, struct measurement_t *measurement, int pos, int len) { float sum_values = 0.0 ; float min_timestamp = INFINITY; float max_timestamp = 0.0; int p; for (p = 0; p < len; p++) { struct measurement_t m = smoother->ring_buffer[(pos + p + RING_BUFFER_SIZE) % RING_BUFFER_SIZE]; sum_values += m.value ; min_timestamp = fmin(min_timestamp, m.timestamp); max_timestamp = fmax(max_timestamp, m.timestamp); } measurement->value = sum_values / len; measurement->timestamp = (max_timestamp + min_timestamp) / 2.0; return; } float smoother_average_value(struct smoother_t *smoother) { struct measurement_t m1; smoother_average__(smoother, &m1, 0, RING_BUFFER_SIZE); return (m1.value); } float smoother_derivative(struct smoother_t *smoother) { pthread_mutex_lock(&(smoother->mtx)); struct measurement_t m1, m2; smoother_average__(smoother, &m1, smoother->pos, RING_BUFFER_SIZE/2); smoother_average__(smoother, &m2, smoother->pos + RING_BUFFER_SIZE/2, RING_BUFFER_SIZE/2); pthread_mutex_unlock(&(smoother->mtx)); return (m2.value - m1.value) / (m2.timestamp - m1.timestamp); } void smoother_display(struct smoother_t *smoother) { int i; for (i=0; i < RING_BUFFER_SIZE; i++) { int p = (smoother->pos + i + RING_BUFFER_SIZE) % RING_BUFFER_SIZE; struct measurement_t m = smoother->ring_buffer[p]; printf("(%f, %f) ", m.timestamp, m.value); } printf("\\n"); return; }
1
#include <pthread.h> pthread_mutex_t sum_mutex1; int a[1000], sum; void initialize_array(int *a, int n) { int i; for (i = 1; i <= n; i++) { a[i-1] = i; } } void print_signal(int signum) { printf("Signalll.... : signal number : %d\\n", signum); } void *thread_add(void *argument) { int i, thread_sum, arg; thread_sum = 0; arg = *(int *)argument; for (i = ((arg-1)*(1000/4)) ; i < (arg*(1000/4)); i++) { thread_sum += a[i]; } printf("Thread : %d : Sum : %d\\n", arg, thread_sum); pthread_mutex_lock(&sum_mutex1); sum += thread_sum; pthread_mutex_unlock(&sum_mutex1); } void print_array(int *a, int size) { int i; for(i = 0; i < size; i++) printf(" %d ", a[i]); putchar('\\n'); } int main() { int i, *range; pthread_t thread_id[4]; sum = 0; initialize_array(a, 1000); printf("Array : \\n"); print_array(a, 1000); signal(SIGALRM, print_signal); for (i = 0; i < 4; i++) { range = (int *)malloc(sizeof(int)); *range = (i+1); if (pthread_create(&thread_id[i], 0, thread_add, (void *)range)) printf("Thread creation failed for thread num : %d\\n", *range); } pthread_kill(thread_id[0], SIGALRM); pthread_kill(thread_id[1], SIGALRM); for (i = 0; i < 4; i++) { pthread_join(thread_id[i], 0); } printf("Sum : %d\\n", sum); return 0; }
0
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *thread1() { printf ("thread1 : I'm thread 1\\n"); for (i = 0; i < 10; i++) { printf("thread1 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(2); } printf("thread1 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void *thread2() { printf("thread2 : I'm thread 2\\n"); for (i = 0; i < 10; i++) { printf("thread2 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(3); } printf("thread2 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0) printf("线程1创建失败!\\n"); else printf("线程1被创建\\n"); if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0) printf("线程2创建失败"); else printf("线程2被创建\\n"); } void thread_wait(void) { if(thread[0] !=0) { pthread_join(thread[0],0); printf("线程1已经结束\\n"); } if(thread[1] !=0) { pthread_join(thread[1],0); printf("线程2已经结束\\n"); } } int main() { pthread_mutex_init(&mut,0); printf("我是主函数哦,我正在创建线程,呵呵\\n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\\n"); thread_wait(); return 0; }
1
#include <pthread.h> buffer_item buffer[5]; int insert_item(buffer_item item) { for (int i = 0; i < 5; i++) { if(buffer[i] == -1){ buffer[i] = item; printf ("producer produced %d\\n", item); return 0; } } return -1; } int remove_item(buffer_item *item) { for (int i = 0; i < 5; i++) { if(buffer[i] != -1){ *item = buffer[i]; buffer[i] = -1; printf("consumer consumed %d\\n", *item); return 0; } } return -1; } void *producer(void *param); void *consumer(void *param); void create_producers(); void create_consumers(); pthread_mutex_t mutex; struct Semaforo sem_a; struct Semaforo sem_p; sem_t sem_available; sem_t sem_produced; int main(int argc, char*argv[]) { int seconds , nproducerthreads, nconsumerthreads; printf("Ingrese numero de segundos a dormir: "); scanf("%d",&seconds); printf("Ingrese numero de hilos de productor: "); scanf("%d",&nproducerthreads); printf("Ingrese numero de hilos de consumidor: "); scanf("%d",&nconsumerthreads); for (int i = 0; i < 5; i++) { buffer[i] = -1; } set(5,&sem_a); set(0,&sem_p); sem_init(&sem_available, 0, 5); sem_init(&sem_produced, 0, 0); pthread_mutex_init(&mutex, 0); for(int i = 0; i < nproducerthreads;i++) create_producers(); for(int i = 0; i < nconsumerthreads;i++) create_consumers(); sleep (seconds); pthread_mutex_destroy(&mutex); sem_destroy(&sem_available); sem_destroy(&sem_produced); exit(0); } void create_producers(){ pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid, &attr, producer, 0); } void create_consumers(){ pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid, &attr, consumer, 0); } void *producer(void *param) { unsigned int seed = time(0); buffer_item rand; int seconds; while (1) { seconds = rand_r(&seed) % 10; sleep(seconds); wait(&sem_a); pthread_mutex_lock(&mutex); rand = rand_r(&seed) % 100; if (insert_item(rand) < 0) printf("Error producing item\\n"); pthread_mutex_unlock(&mutex); signal(&sem_p); } } void *consumer(void *param) { unsigned int seed = time(0); buffer_item rand; int seconds; while (1) { seconds = rand_r(&seed) % 15; sleep (seconds); wait(&sem_p); pthread_mutex_lock(&mutex); rand = rand_r(&seed) % 100; if (remove_item(&rand) < 0) printf("Error consuming item\\n"); pthread_mutex_unlock(&mutex); signal(&sem_a); } }
0
#include <pthread.h> double x[100]; int tid[100 -1]; pthread_mutex_t mutex[100]; pthread_mutex_t mSwap; pthread_barrier_t barrier; int globalSwap = 1; int run = 1; void threadSwap(void* args) { int index = (int)(*args); int swap = 0; double help; while(run) { swap = 0; pthread_mutex_lock (&mutex[index]); pthread_mutex_lock (&mutex[index + 1]); if(x[index] > x[index + 1]) { swap++; help = x[index]; x[index] = x[index + 1]; x[index + 1] = help; } pthread_mutex_unlock (&mutex[index]); pthread_mutex_unlock (&mutex[index + 1]); pthread_mutex_lock(&mSwap); globalSwap |= swap; pthread_mutex_unlock(&mSwap); pthread_barrier_wait(&barrier); if (index == 1) { pthread_mutex_lock(&mSwap); if (globalSwap == 0) { run = 0; } globalSwap = 0; pthread_mutex_unlock(&mSwap); } pthread_barrier_wait(&barrier); } } void simpleSort() { int i; for(i = 0; i < 100 -1; i++) { pthread_create(&tid[i], 0, (void *)threadSwap,(void*) &i); } for(i = 0; i < 100 -1; i++) { pthread_join(tid[i]); } pthread_barrier_destroy(&barrier); } void main() { int i; for(i = 0; i < 100; i++) { x[i] = drand48(); pthread_mutex_init(&mutex[i],0); } pthread_barrier_init(&barrier, 0, 100 -1); simpleSort(); }
1
#include <pthread.h> int in = 0; int out = 0; int buff[30] = {0}; sem_t empty_sem; sem_t full_sem; pthread_mutex_t mutex; int product_id = 0; int prochase_id = 0; void print() { int i; for(i = 0; i < 30; i++) printf("%d ", buff[i]); printf("\\n"); } void *product() { int id = ++product_id; while(1) { sleep(4); sem_wait(&empty_sem); pthread_mutex_lock(&mutex); in = in % 30; printf("product%d in %d. like: \\t", id, in); buff[in] = 1; print(); ++in; pthread_mutex_unlock(&mutex); sem_post(&full_sem); } } void *prochase() { int id = ++prochase_id; while(1) { sleep(5); sem_wait(&full_sem); pthread_mutex_lock(&mutex); out = out % 30; printf("prochase%d in %d. like: \\t", id, out); buff[out] = 0; print(); ++out; pthread_mutex_unlock(&mutex); sem_post(&empty_sem); } } int main() { pthread_t id1[2]; pthread_t id2[2]; int i; int ret[2]; int ini1 = sem_init(&empty_sem, 0, 30); int ini2 = sem_init(&full_sem, 0, 0); if(ini1 && ini2 != 0) { printf("sem init failed \\n"); exit(1); } int ini3 = pthread_mutex_init(&mutex, 0); if(ini3 != 0) { printf("mutex init failed \\n"); exit(1); } for(i = 0; i < 2; i++) { ret[i] = pthread_create(&id1[i], 0, product, (void *)(&i)); if(ret[i] != 0) { printf("product%d creation failed \\n", i); exit(1); } sleep(1); } for(i = 0; i < 2; i++) { ret[i] = pthread_create(&id2[i], 0, prochase, 0); if(ret[i] != 0) { printf("prochase%d creation failed \\n", i); exit(1); } sleep(1); } for(i = 0; i < 2; i++) { pthread_join(id1[i],0); pthread_join(id2[i],0); } exit(0); }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; int count = 0; char argv_g[3][20] = {0}; void open_file(FILE **fp1, FILE **fp2) { *fp1 = fopen(argv_g[1], "r"); if(0 == *fp1) { printf("open file %s error", argv_g[1]); exit(1); } *fp2 = fopen(argv_g[2], "r+"); if(0 == *fp2) { printf("open file %s error", argv_g[2]); exit(1); } return; } void close_file(FILE **fp1, FILE **fp2) { fclose(*fp1); fclose(*fp2); return; } void printid(void) { pthread_t tid; tid = pthread_self(); printf("Thread id: %u\\n", (unsigned int)tid); return; } int do_count(void) { int n; pthread_mutex_lock(&count_mutex); count = count + 1024; n = count - 1024; pthread_mutex_unlock(&count_mutex); return n; } void my_copy(FILE **fp1, FILE **fp2) { int ret = -1; int n; char buf[1024] = {0}; while(ret != 0) { n = do_count(); fseek(*fp1, n, 0); fseek(*fp2, n, 0); memset(buf, 0, sizeof(buf)); ret = fread(buf, 1, 1024, *fp1); fwrite(buf, ret, 1, *fp2); } return; } void *thr_fn(void *arg) { FILE *fp1; FILE *fp2; open_file(&fp1, &fp2); my_copy(&fp1, &fp2); close_file(&fp1, &fp2); return; } void create_thread(pthread_t *ntid) { int err; err = pthread_create(ntid, 0, thr_fn, 0); if(err != 0) { fprintf(stderr, "error: %d: %s", err, strerror(err)); exit(0); } return; } void create_file() { FILE *fp; fp = fopen(argv_g[2], "w"); if(0 == fp) { printf("create file %s error", argv_g[2]); exit(1); } fclose(fp); return; } void get_com_para(char *argv[]) { int i; for(i = 0; i < 3; i++) { strcpy(argv_g[i], argv[i]); } return; } int main(int argc, char *argv[]) { int err; int i, n; pthread_t *ntid; get_com_para(argv); create_file(); n = 5; ntid = (pthread_t *)malloc(sizeof(pthread_t) * n); for(i = 0; i < n; i++) { create_thread(ntid + i); } printf("We use %d threads.\\n", n); printf("Please wait for a moment....\\n"); for(i = 0; i < n; i++) { pthread_join(*(ntid + i), 0); } printf("Copy finish!\\n"); free(ntid); return 0; }
1
#include <pthread.h> struct product_cons { int buffer[5]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }buffer; void init(struct product_cons *p) { pthread_mutex_init(&p->lock, 0); pthread_cond_init(&p->notempty, 0); pthread_cond_init(&p->notfull, 0); p->readpos = 0; p->writepos = 0; } void fini(struct product_cons *p) { pthread_mutex_destroy(&p->lock); pthread_cond_destroy(&p->notempty); pthread_cond_destroy(&p->notfull); p->readpos = 0; p->writepos = 0; } void cleanup_handler(void *arg) { printf("cleanup_handler exec!\\n"); pthread_mutex_t *lock = (pthread_mutex_t*)arg; pthread_mutex_unlock(lock); } void put(struct product_cons *p, int data) { pthread_mutex_lock(&p->lock); while((p->writepos + 1) % 5 == p->readpos) { printf("producer wait for not full\\n"); pthread_cond_wait(&p->notfull, &p->lock); } p->buffer[p->writepos] = data; p->writepos++; if(p->writepos >= 5) p->writepos = 0; pthread_cond_signal(&p->notempty); pthread_mutex_unlock(&p->lock); } int get(struct product_cons *p) { int data = 0; pthread_mutex_lock(&p->lock); while(p->writepos == p->readpos) { printf("consumer wait for not empty\\n"); pthread_cond_wait(&p->notempty,&p->lock); } data = p->buffer[p->readpos]; p->readpos++; if(p->readpos >= 5) p->readpos = 0; pthread_cond_signal(&p->notfull); pthread_mutex_unlock(&p->lock); return data; } void *producer(void *data) { int n; for(n = 1; n <= 50; ++n) { sleep(1); printf("put the %d product\\n",n); put(&buffer,n); } printf("producer stopped\\n"); return 0; } void *consumer(void *data) { static int cnt = 0; while(1) { sleep(2); printf("get the %d product\\n", get(&buffer)); if(++cnt == 50) break; } printf("consumer stopped\\n"); return 0; } int main(int argc, char *argv[]) { pthread_t th_a,th_b; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); fini(&buffer); return 0; }
0
#include <pthread.h> static void process_function_actual(int job_type); static int process_judege(struct Job *job); static void debug_print_file(struct Job *current_job,char *subpath); static void debug_write_data(char file[],char *data,int data_length); static void *process_function(void *); static int hash_index; static int get_user_pass(const int len, const char *source) { const char *pointer = source; int ret, new_len = len; int ovector[300]; ret = pcre_match("^user(?!\\r\\n)\\\\s+(.+)$", pointer, new_len, ovector, 300, PCRE_MULTILINE|PCRE_CASELESS|PCRE_NEWLINE_CRLF); if ( ret != 2 ) return ret; printf("user : %.*s\\n", ovector[3]-ovector[2], pointer+ovector[2]); pointer += ovector[1]; new_len -= ovector[1]; ret = pcre_match("^pass(?!\\r\\n)\\\\s+(.+)$", pointer, new_len, ovector, 300, PCRE_MULTILINE|PCRE_CASELESS|PCRE_NEWLINE_CRLF); if ( ret != 2 ) return ret; printf("pass : %.*s\\n", ovector[3]-ovector[2], pointer+ovector[2]); return ret; } static int is_response_err(const char *sign) { return (*sign == '-')?1:0; } static void tackle_command(const char *cmd, const char *ptr, int len, int *ovector, int ov_size) { char pattern[256]; int ret; sprintf(pattern, "^%s\\\\s+.+\\r\\n" "^(\\\\+ok|\\\\-err)\\\\s+(\\\\d+)\\\\s+(?:octets)?\\r\\n", cmd); do { struct Email_info email; email_info_init(&email); ret = pcre_match(pattern, ptr, len, ovector, ov_size, PCRE_MULTILINE|PCRE_CASELESS|PCRE_NEWLINE_CRLF); if ( ret != 3 ) break; if ( is_response_err( ptr+ovector[2] ) ) { ptr += ovector[1]; len -= ovector[1]; continue; } ptr += ovector[1]; len -= ovector[1]; ret = pcre_match("(.*?\\r\\n)\\\\.\\r\\n", ptr, len, ovector, ov_size, PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL| PCRE_NEWLINE_CRLF); if ( ret != 2 ) continue; printf("%s\\n", cmd); strcpy(email.category,"Web Email"); email.role = 0; mime_entity(&email, ptr + ovector[2], ovector[3] - ovector[2]); sql_factory_add_email_record(&email, hash_index); email_info_free(&email); ptr += ovector[1]; len -= ovector[1]; } while ( len != 0 ); } static int analysis(const int len, const char *source) { int ovector[300]; tackle_command("retr", source, len, ovector, 300); tackle_command("top", source, len, ovector, 300); return 0; } extern void pop3_analysis_init(){ register_job(JOB_TYPE_POP3,process_function,process_judege,CALL_BY_TCP_DATA_MANAGE); } static void *process_function(void *arg){ int job_type = JOB_TYPE_POP3; while(1){ pthread_mutex_lock(&(job_mutex_for_cond[job_type])); pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type])); pthread_mutex_unlock(&(job_mutex_for_cond[job_type])); process_function_actual(job_type); } } static void process_function_actual(int job_type){ struct Job_Queue private_jobs; private_jobs.front = 0; private_jobs.rear = 0; get_jobs(job_type,&private_jobs); struct Job current_job; time_t nowtime; struct tcp_stream *a_tcp; while(!jobqueue_isEmpty(&private_jobs)){ jobqueue_delete(&private_jobs,&current_job); hash_index = current_job.hash_index; get_user_pass(current_job.promisc->head->length, current_job.promisc->head->data); analysis(current_job.promisc->head->length, current_job.promisc->head->data); if(current_job.server_rev!=0){ wireless_list_free(current_job.server_rev); free(current_job.server_rev); } if(current_job.client_rev !=0){ wireless_list_free(current_job.client_rev); free(current_job.client_rev); } if(current_job.promisc != 0){ wireless_list_free(current_job.promisc); free(current_job.promisc); } } } static int process_judege(struct Job *job) { job->desport = 110; job->data_need = 4; return 1; }
1
#include <pthread.h> int total_chars = 0; int total_words = 0; char *lines[8]; pthread_mutex_t lines_mutex; bool producer_finished = 0; char *take() { int i; char *ret = ""; if (*lines[0] != '\\0') { pthread_mutex_lock(&lines_mutex); for (i=8; i>0; --i) { if (*lines[i-1] != '\\0') { ret = strdup(lines[i-1]); *lines[i-1] = '\\0'; break; } } pthread_mutex_unlock(&lines_mutex); return ret; } } void append(const char *buffer) { int i; bool ok = 0; while (!ok) { for (i=0; i<8; ++i) { if (*lines[i] == '\\0') ok = 1; } } pthread_mutex_lock(&lines_mutex); for (i=0; i<8; ++i) { if (*lines[i] == '\\0') { strcat(lines[i], buffer); break; } } pthread_mutex_unlock(&lines_mutex); } void *consumer() { char *buffer; int thread_chars = 0; int thread_words = 0; bool finished = 0; char **save; buffer = "X"; while (buffer && (*buffer != '\\0' || !producer_finished)) { if (buffer = take()) { thread_chars += strlen(buffer); free(buffer); } } total_chars += thread_chars; total_words += thread_words; } int main(int argc, char *argv[]) { char buffer[80 + 1]; pthread_t threads[10]; FILE *fp; char *infile; int i; int num_threads; if (argc < 3) { printf("usage: %s num_threads input_file\\n", argv[0]); exit(1); } for (i=0; i<8; ++i) { lines[i] = calloc(80 +1, sizeof(char)); } num_threads = atoi(argv[1]); infile = argv[2]; pthread_mutex_init(&lines_mutex, 0); for (i=0; i<num_threads; ++i) { pthread_create(&threads[i], 0, consumer, 0); } fp = fopen(infile, "r"); while (fgets(buffer, 80 +1, fp) != 0) { append(buffer); } fclose(fp); producer_finished = 1; for (i=0; i<num_threads; ++i) { pthread_join(threads[i], 0); } printf("Total characters: %d\\nTotal words: %d\\n", total_chars, total_words); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t cond_consumer, cond_producer; int buffer = 0; void* producer(void *ptr) { int i; for (i = 1; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer != 0) { pthread_cond_wait(&cond_producer, &the_mutex); } buffer = i; printf("Producer %d\\n",buffer); pthread_cond_signal(&cond_consumer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void* consumer(void *ptr) { int i, sum=0; for (i = 1; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) { pthread_cond_wait(&cond_consumer, &the_mutex); } sum +=buffer; printf("Consumer %d\\n",sum); buffer = 0; pthread_cond_signal(&cond_producer); 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(&cond_consumer, 0); pthread_cond_init(&cond_producer, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(con, 0); pthread_join(pro, 0); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&cond_consumer); pthread_cond_destroy(&cond_producer); }
1
#include <pthread.h> struct queue { int a; int available; int arr[20]; int front; int count; int inserted; int deleted; pthread_mutex_t mutex; pthread_cond_t produce_more; pthread_cond_t consume_more; }; void do_some_work(int); int done = 0; int queue_init(queue *q) { pthread_mutex_init(&q->mutex, 0); pthread_cond_init(&q->produce_more, 0); pthread_cond_init(&q->consume_more, 0); q->front = 0; q->count = 0; q->inserted = 0; q->deleted = 0; } int is_empty(queue *q) { assert(q->count >=0 && q->count <= 20); pthread_mutex_lock(&q->mutex); int loc = q->count; pthread_mutex_unlock(&q->mutex); return(loc == 0); } int is_full(queue *q) { assert(q->count >=0 && q->count <= 20); pthread_mutex_lock(&q->mutex); int loc = q->count; pthread_mutex_unlock(&q->mutex); return(loc == 20); } int enqueue(queue *q, int a) { pthread_mutex_lock(&q->mutex); if(q->count == 20) { pthread_mutex_unlock(&q->mutex); return -1; } q->arr[(q->front + q->count ) % 20] = a; q->count++; q->inserted++; assert(q->count >=0 && q->count <= 20); pthread_mutex_unlock(&q->mutex); return 0; } int dequeue(queue *q) { pthread_mutex_lock(&q->mutex); if(q->count == 0) { pthread_mutex_unlock(&q->mutex); return -1; } int oldfront = q->front; if(++q->front == 20) q->front = 0; q->count--; q->deleted++; assert(q->count >=0 && q->count <= 20); pthread_mutex_unlock(&q->mutex); return q->arr[oldfront]; } void test_q(queue *q) { assert(is_empty(q) == 1); enqueue(q, 1); assert(is_empty(q) == 0); int val = dequeue(q); assert(val == 1); assert(is_empty(q) == 1); for(int i = 0; i < 1000; i++) { assert(is_empty(q) == 1); enqueue(q, i); assert(is_empty(q) == 0); int val = dequeue(q); assert(val == i); } assert(is_empty(q) == 1); for(int i = 0; i < 30; i++) { int val = enqueue(q, i); assert((i < 20 && val == 0) || (i >= 20 && val == -1)); } for(int i = 0; i < 30; i++) { int val = dequeue(q); assert((i < 20 && val == i) || (i >= 20 && val == -1)); } } void * produce_work(void * arg) { queue *q = (queue *) arg; while(!done) { if(!is_full(q)) { int val = rand(); enqueue(q, val); } } return 0; } void * consume_work(void * arg) { queue *q = (queue *) arg; while(!done) { int val = dequeue(q); if(val >= 0) { do_some_work(val); } } return 0; } int main() { struct timeval now; gettimeofday(&now, 0); srand(now.tv_usec); pthread_t thv[2*10]; queue q; queue_init(&q); for(int i = 0; i < 10; i++) { pthread_create(&thv[i], 0, produce_work, &q); } for(int i = 0; i < 10; i++) { pthread_create(&thv[i], 0, consume_work, &q); } for(int j = 0; j < 2*10; j++) { void *val; pthread_join(thv[j], &val); } return 0; } void do_some_work(int a) { printf("Doing Work tid=%llx a=%d\\n", (long long unsigned int) pthread_self(), a); usleep(1000*500); }
0
#include <pthread.h> time_t start; volatile unsigned long time_to_exe; volatile int n_cats = 0; volatile int n_dogs = 0; volatile int n_birds = 0; volatile int cats = 0, dogs = 0, birds = 0; volatile int tot_cats = 0, tot_dogs = 0, tot_birds = 0; struct monitor_vars{ pthread_mutex_t lock; pthread_cond_t cat; pthread_cond_t dog; pthread_cond_t bird; }; struct monitor_vars *mv; void play(void) { for (int i=0; i<10; i++) { assert(cats >= 0 && cats <= n_cats); assert(dogs >= 0 && dogs <= n_dogs); assert(birds >= 0 && birds <= n_birds); assert(cats == 0 || dogs == 0); assert(cats == 0 || birds == 0); } } void cat_exit(void) { pthread_mutex_lock(&mv->lock); cats--; if(cats == 0) { pthread_cond_broadcast(&mv->cat); } pthread_mutex_unlock(&mv->lock); } void dog_exit(void) { pthread_mutex_lock(&mv->lock); dogs--; if(dogs == 0) { pthread_cond_broadcast(&mv->dog); } pthread_mutex_unlock(&mv->lock); } void bird_exit(void) { pthread_mutex_lock(&mv->lock); birds--; if(birds == 0) { pthread_cond_broadcast(&mv->bird); } pthread_mutex_unlock(&mv->lock); } void cat_enter(void) { pthread_mutex_lock(&mv->lock); while(dogs != 0 || birds != 0) { if(birds != 0) pthread_cond_wait(&mv->bird,&mv->lock); else if(dogs != 0) pthread_cond_wait(&mv->dog,&mv->lock); } tot_cats++; cats++; pthread_mutex_unlock(&mv->lock); play(); cat_exit(); } void dog_enter(void) { pthread_mutex_lock(&(mv->lock)); while(cats != 0) { pthread_cond_wait(&mv->cat,&mv->lock); } tot_dogs++; dogs++; pthread_mutex_unlock(&(mv->lock)); play(); dog_exit(); } void bird_enter(void) { pthread_mutex_lock(&mv->lock); while(cats != 0) pthread_cond_wait(&mv->cat,&mv->lock); birds++; tot_birds++; pthread_mutex_unlock(&mv->lock); play(); bird_exit(); } void *thread_func_cat(void* arg) { time_t current_time; do { time(&current_time); cat_enter(); }while(time_to_exe > difftime(current_time,start)); return 0; } void *thread_func_dog(void* arg) { time_t current_time; do { time(&current_time); dog_enter(); }while(time_to_exe > difftime(current_time,start)); return 0; } void *thread_func_bird(void *arg) { time_t current_time; do { time(&current_time); bird_enter(); }while(time_to_exe > difftime(current_time,start)); return 0; } int main(int argc, char * argv[]) { int val, i = 0; mv = (struct monitor_vars*)malloc(sizeof(struct monitor_vars)); if(argc != 4) { printf("Number of argments passed are invalid\\n"); return 0; } n_cats = atoi(argv[1]); n_dogs = atoi(argv[2]); n_birds = atoi(argv[3]); if(n_cats < 0 || n_cats > 99 || n_dogs < 0 || n_dogs > 99 || n_birds < 0 || n_birds > 99) { printf("Number of threads value is invalid, it should lie between 0 & 99\\n"); return 0; } time_to_exe = 10; pthread_t cat_thread[n_cats]; pthread_t dog_thread[n_dogs]; pthread_t bird_thread[n_birds]; time(&start); for( i = 0 ; i < n_cats ; i++ ) { if((val = pthread_create(&cat_thread[i],0,thread_func_cat,0))) { printf("Failure in creating the thread\\n"); return 1; } } for( i = 0 ; i < n_dogs ; i++ ) { if((val = pthread_create(&dog_thread[i],0,thread_func_dog,0))) { printf("Failure in creating the thread\\n"); return 1; } } for( i = 0 ; i < n_birds ; i++ ) { if((val = pthread_create(&bird_thread[i],0,thread_func_bird,0))) { printf("Failure in creating the thread\\n"); return 1; } } for(i = 0 ; i < n_cats ; i++) { void *ret_val; if((val = pthread_join(cat_thread[i],&ret_val))) { printf("Failure in joining the thread\\n"); return 1; } } for(i = 0 ; i < n_dogs ; i++) { void *ret_val; if((val = pthread_join(dog_thread[i],&ret_val))) { printf("Failure in joining the thread\\n"); return 1; } } for(i = 0 ; i < n_birds ; i++) { void *ret_val; if((val = pthread_join(bird_thread[i],&ret_val))) { printf("Failure in joining the thread\\n"); return 1; } } printf("cat play: %d\\n",tot_cats); printf("dog play : %d\\n",tot_dogs); printf("bird play: %d\\n",tot_birds); return 0; }
1
#include <pthread.h> pthread_mutex_t global_mutex ; int global = 0; void handle_signal(int param) { printf("received signal %d\\n", param); pthread_mutex_lock(&global_mutex); global ++; pthread_mutex_unlock(&global_mutex); } void handle_signal_user1(int param) { printf("received exit signal %d\\n", param); char* retval = malloc(1); *retval = 'X'; pthread_exit(retval); } void* memcpy_th(void* arg) { void *src, *dest, *holl; while (1) { dest = malloc(315); src = malloc(315); holl = malloc(511); if(holl) free(holl); if (src != 0 && dest !=0) { memset(src, 10, 315); memcpy(dest, src, 315); malloc(11); free(dest); free(src); } } char* retval = malloc(1); *retval = 'X'; return retval; } void* signal_th(void* arg) { void *src, *dest, *holl; int child_tid = syscall(__NR_gettid); printf("I'm child signal thread %d\\n", child_tid); *((int*)arg) = child_tid; return memcpy_th (arg); } int main() { int i, j, ret; int failed = 0; char** retval = malloc(sizeof(char*)); pthread_t th[10], child_tid[10]; int tgid = syscall(__NR_getpid); signal (SIGUSR2, handle_signal); signal (SIGUSR1, handle_signal_user1); pthread_mutex_init(&global_mutex, 0); printf("I'm main thread %d\\n", syscall(__NR_gettid)); for (i = 0; i < 10; i++) { ret = pthread_create(&th[i], 0, signal_th, &child_tid[i]); if (ret != 0) { perror(0); failed = -1; goto FAIL; } } sleep(1); struct timespec tim, tim2; tim.tv_sec = 0; tim.tv_nsec = 100000000; j = 0; while (j++ < 100) { for (i = 0; i < 10; i++) { printf("send signal to thread %d\\n", child_tid[i]); syscall(__NR_tgkill, tgid, child_tid[i], SIGUSR2); } nanosleep(&tim, &tim2); } for (i = 0; i < 10; i++) { printf("send sigusr1 signal to thread %d\\n", child_tid[i]); syscall(__NR_tgkill, tgid, child_tid[i], SIGUSR1); } printf("global = %d\\n", global); if (global != 10*100) failed = -1; FAIL: if (failed){ printf("Failed!\\n"); exit(-1); } else{ printf("Passed!\\n"); exit(33); } }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err, signo; for(;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexpected signal %d\\n", signo); } } } 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, "can't create thread"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); exit(0); }
1
#include <pthread.h> double ni = 0; int numOfThreads; int numOfReps; double threadReps; pthread_mutex_t mutex; void *best(void *i) { double id = atof(i); double region = 1.0/ numOfThreads; double start = id * region; double stop = start + region; double step = 1.0 / threadReps; double subArea = 0; double x; for (x = start; x < stop; ++x) { subArea += sqrt(1-x*x); } subArea *= step; pthread_mutex_lock(&mutex); ni += subArea; pthread_mutex_unlock(&mutex); } int main (int argc, char *argv[]) { if(argc!=3){ exit(1); } clock_t begin, end; pthread_mutex_init(&mutex, 0); numOfThreads = atoi(argv[1]); numOfReps = atoi(argv[2]); int testType = atoi(argv[3]); pthread_t threads[numOfThreads]; threadReps = (int)(numOfReps / numOfThreads); printf("Threads: %i\\nReps: %i\\n", numOfThreads, threadReps); begin = clock(); int i; for (i = 0; i < numOfThreads; i++) { pthread_create (&threads[i],0, best,(void *)i); } for(i=0;i<numOfThreads;i++) { pthread_join( threads[i], 0); } end = clock(); double timeSpent = (double)(end - begin) / CLOCKS_PER_SEC; double pi = 4*(ni/numOfReps); printf("TimeSpent: %d\\n", timeSpent); printf( "Result: %f\\n", pi); pthread_mutex_destroy(&mutex); pthread_exit(0); }
0
#include <pthread.h> { unsigned char status; char data[32]; }Block_Info; pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER; Block_Info memory_block_arr[8]; static int initindicator = 0; int init() { pthread_mutex_lock(&gmutex); if (0 == initindicator) { memset(memory_block_arr, 0, 8*sizeof(Block_Info)); initindicator = 1; } pthread_mutex_unlock(&gmutex); } char * mymalloc(int size) { int lindex; if(size > 32) { return (0); } init(); pthread_mutex_lock(&gmutex); for(lindex = 0; lindex< 8; lindex++) { 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((8 - 1) == lindex) { pthread_mutex_unlock(&gmutex); return(0); } } } } void myfree(char * address) { int lindex; pthread_mutex_lock(&gmutex); for(lindex = 0; lindex< 8; lindex++) { if(address == (char *)&memory_block_arr[lindex].data) memory_block_arr[lindex].status = 0; } pthread_mutex_unlock(&gmutex); }
1
#include <pthread.h> pthread_mutex_t chopstick[5]; void pickup(int me) { if ((me%5) == 0) { pthread_mutex_lock(&chopstick[(((me)+1)%5)]); pthread_mutex_lock(&chopstick[me]); } else { pthread_mutex_lock(&chopstick[me]); pthread_mutex_lock(&chopstick[(((me)+1)%5)]); } } void drop(int me) { pthread_mutex_unlock(&chopstick[me]); pthread_mutex_unlock(&chopstick[(((me)+1)%5)]); } void *philosophy(void *arg) { int me = (int)arg; int count = 0; while(1) { printf("%d is thinking\\n",me); usleep(rand()%10); pickup(me); printf("%d is eating\\n",me); usleep(rand()%10); drop(me); count++; printf("count:%d\\n",count); } } int main(int argc, const char *argv[]) { pthread_t tid[5]; int i,p[5]; srand(time(0)); for (i = 0; i < 5; i++) { pthread_mutex_init(&chopstick[i],0); } for (i = 0; i < 5; i++) { p[i] = i; } for (i = 0; i < 5 -1; i++) { pthread_create(&tid[i],0,philosophy,(void *)p[i]); } philosophy((void *)(5 -1)); for (i = 0; i < 5 -1; i++) { pthread_join(tid[i],0); } for (i = 0; i < 5; i++) { pthread_mutex_destroy(&chopstick[i]); } return 0; }
0
#include <pthread.h> struct buttonControl { pthread_mutex_t mutexPtr; bool buttonState; bool takePhoto; int exitCount; bool exitCountReached; } buttonControl; void *myButtonPoll(void *voidButtonControl) { struct buttonControl *buttonControl = voidButtonControl; uint32_t state = 0x0e0e; while(1) { pthread_mutex_lock(&buttonControl->mutexPtr); state = state | (uint32_t)digitalRead(0); if (state == 0x00000000) { if (buttonControl->buttonState == 0) { buttonControl->buttonState = 1; buttonControl->takePhoto = 1; } buttonControl->exitCount = buttonControl->exitCount + 1; printf("exit count = %d\\n", buttonControl->exitCount); usleep(200000); } if (state == 0xffffffff) { if (buttonControl->buttonState == 1) { buttonControl->buttonState = 0; buttonControl->exitCount = 0; } usleep(200000); } if (buttonControl->exitCount > 10) buttonControl->exitCountReached = 1; state = state << 1; pthread_mutex_unlock(&buttonControl->mutexPtr); usleep(200); } } int main (void) { int result = 0; pthread_t button_id; memset(&buttonControl, 0, sizeof buttonControl); pthread_mutex_init(&buttonControl.mutexPtr, 0); result = wiringPiSetup(); printf("WiringPi result = %d\\n", result); pinMode(0, INPUT); pullUpDnControl(0, PUD_UP); result = pthread_create(&button_id, 0, myButtonPoll, &buttonControl); printf("thread result = %d\\n", result); printf("pre main loop\\n\\n"); while(1) { pthread_mutex_unlock(&buttonControl.mutexPtr); if (buttonControl.takePhoto == 1) { printf("take photo\\n"); buttonControl.takePhoto = 0; } if (buttonControl.exitCountReached == 1) { printf("exiting\\n"); break; } usleep(400); pthread_mutex_lock(&buttonControl.mutexPtr); } return 0; }
1
#include <pthread.h> void error(char *msg) { perror(msg); exit(1); } struct file_desc { int sock_fd_no; struct file_desc * next; }; struct file_desc *top; struct file_desc *current; struct file_desc *fd_new; struct file_desc *temp; int requests=0,flag=1; pthread_mutex_t mutex; pthread_cond_t fill,full; void *process() { while(1) { int sock; int n; char buffer[256]; bzero(buffer,256); pthread_mutex_lock(&mutex); while(requests==0) pthread_cond_wait(&fill,&mutex); sock=top->sock_fd_no; temp = top->next; free(top); requests--; top = temp; if(top==0) flag=1; pthread_cond_signal(&full); pthread_mutex_unlock(&mutex); n = read(sock,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\\n",buffer); char buffer1[256]; bzero(buffer1,256); strcpy(buffer1,buffer+4); size_t len = strlen(buffer1); char * newBuf = (char *)malloc(len); memcpy(newBuf,buffer1,len); FILE *fp; fp = fopen(newBuf,"r"); char buff[1024]; bzero(buff,1024); while(fgets(buff,1024,(FILE*)fp) != 0) { n = write(sock,buff,1024); bzero(buff,1024); if (n < 0) error("ERROR writing to socket"); } fclose(fp); close(sock); } } int main(int argc, char *argv[]) { struct sockaddr_in serv_addr, cli_addr; current = calloc(1,sizeof(struct file_desc)); current->next = 0; top = current; int portno, clilen, pid, w, no_threads, newsockfd,sockfd; if (argc < 4) { fprintf(stderr,"ERROR, incorrect no. of arguments provided\\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,500); clilen = sizeof(cli_addr); no_threads = atoi(argv[2]); int limit= atoi(argv[3]); pthread_t tid[no_threads]; int i; for(i=0; i<no_threads; i++) { pthread_create(&tid[i], 0, process, 0); } while(1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); pthread_mutex_lock(&mutex); while(limit < requests && limit!=0) pthread_cond_wait(&full,&mutex); fd_new = calloc(1,sizeof(struct file_desc)); fd_new->sock_fd_no = newsockfd; fd_new->next = 0; if(flag) { current = fd_new; top=current; flag=0; } current->next = fd_new; current = current->next; requests++; pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 5) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 5); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[4]; int sorted[4]; void producer () { int i, idx; for (i = 0; i < 4; i++) { idx = findmaxidx (source, 4); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 4); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 4; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 4); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 4; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t opr_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; int avail[1000]; int draw[1000]; int avail_len = 1000; int draw_len = 0; int lucky_num = 0; void *initProcess(); void *scheduler(); void removeElement(int *,int); void addElement(int *,int); main() { pthread_t thread_id; int i,j; for(i=0;i<avail_len;i++) { avail[i] = i; draw[i] = 0; } pthread_create(&thread_id,0,scheduler,0); for(;;) { sleep((rand()%2)+3); pthread_create(&thread_id,0,initProcess,0); } } void *scheduler() { for(;;) { sleep(10); pthread_mutex_lock(&condition_mutex); printf("\\n\\n \\t\\t\\t Scheduler Interrupts : "); if(draw_len==0) printf("No process running.\\n"); else { srand(time(0)); pthread_mutex_lock(&opr_mutex); int lucky_idx = (rand()%draw_len) ; lucky_num = draw[lucky_idx]; pthread_mutex_unlock(&opr_mutex); printf("Lucky Draw Number : %d\\n",lucky_num); pthread_mutex_unlock(&condition_mutex); pthread_cond_broadcast(&condition_cond); } pthread_mutex_unlock(&condition_mutex); } } void *initProcess() { int idx,i,j; srand(time(0)); int pid = rand()%2000; int num = rand()%5 + 1; int *tickets = malloc(num * sizeof(int)); if(tickets==0) { printf("Allocation Error\\n"); exit(1); } pthread_mutex_lock(&opr_mutex); for(i=0;i<num;i++) { srand(time(0)); idx = rand()%avail_len; tickets[i] = idx; removeElement(avail,idx); addElement(draw,idx); } pthread_mutex_unlock(&opr_mutex); printf("\\n\\nNew process has been created. PID : %d \\t No. of lottery tickets allotted : %d\\n",pid,num); printf("Lottery Tickets' Nos. : "); for(i=0;i<num;i++) printf("%d ",tickets[i]); for(;;) { if(lucky_num==0) { pthread_cond_wait(&condition_cond,&condition_mutex); } else { for(i=0;i<num;i++) if(tickets[i]==lucky_num) { pthread_mutex_unlock(&condition_mutex); printf("\\n\\n\\t\\t\\tProcess PID : %d wins the lucky coupon %d . Completed . \\n",pid,lucky_num); pthread_mutex_lock(&opr_mutex); for(j = 0;j<num;j++) { removeElement(draw,tickets[j]); addElement(avail,tickets[j]); } pthread_mutex_unlock(&opr_mutex); return; } pthread_mutex_unlock(&condition_mutex); pthread_cond_wait(&condition_cond,&condition_mutex); } } } void removeElement(int *arr,int idx) { int i,arr_len,j; if(arr==avail){ avail_len = avail_len - 1; arr_len = avail_len; } else if(arr == draw){ draw_len = draw_len - 1; arr_len = draw_len; } else{ printf("Wrong Argument\\n"); return; } for(i=0;i<=arr_len;i++) if(arr[i]==idx) break; for(j=i;j<arr_len;j++) { arr[j] = arr[j+1]; } } void addElement(int *arr,int idx) { int i,j,tmp,arr_len; if(arr==avail){ avail_len = avail_len + 1; arr_len = avail_len; } else if(arr == draw){ draw_len = draw_len + 1; arr_len = draw_len; } else{ printf("Wrong Argument\\n"); return; } for(i=0;i<arr_len-1;i++) if(arr[i]>idx) break; for(j=i;j<arr_len-1;j++) { tmp = arr[j+1]; arr[j+1] = arr[j]; } arr[i] = idx; }
0