text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static pthread_mutex_t atomic_lock = PTHREAD_MUTEX_INITIALIZER; void avpriv_atomic_lock(void) { pthread_mutex_lock(&atomic_lock); } void avpriv_atomic_unlock(void) { pthread_mutex_unlock(&atomic_lock); }
1
#include <pthread.h> void *thread_function(void *); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; main() { pthread_t thread_id[10]; int i, j; for(i=0; i < 10; i++) { pthread_create( &thread_id[i], 0, thread_function, 0 ); } for(j=0; j < 10; j++) { pthread_join( thread_id[j], 0); } printf("Final counter value: %d\\n", counter); } void *thread_function(void *dummyPtr) { printf("Thread number %ld\\n", pthread_self()); pthread_mutex_lock( &mutex1 ); counter++; pthread_mutex_unlock( &mutex1 ); }
0
#include <pthread.h> uint16_t get_sequence(uint16_t *seq, pthread_mutex_t *lock) { uint16_t ret; pthread_mutex_lock(lock); ret=(*seq)++; pthread_mutex_unlock(lock); return ret; } uint16_t get_id(uint16_t *id, pthread_mutex_t *lock) { uint16_t ret; pthread_mutex_lock(lock); ret=(*id)++; if(ret==CTRL_ID) ret=(*id)++; pthread_mutex_unlock(lock); return ret; } void set_sequence(uint16_t value, uint16_t *seq, pthread_mutex_t *lock) { pthread_mutex_lock(lock); *seq=value; pthread_mutex_unlock(lock); }
1
#include <pthread.h> void * create_mutex() { pthread_mutex_t * m = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init ( m, 0 ); return m; } void destroy_mutex ( void * m ) { pthread_mutex_t * _m = ( pthread_mutex_t* ) m; pthread_mutex_destroy ( _m ); free(m); } void lock_mutex ( void * m ) { pthread_mutex_t * _m = ( pthread_mutex_t* ) m; pthread_mutex_lock ( _m ); } void free_mutex ( void *m ) { pthread_mutex_t * _m = ( pthread_mutex_t* ) m; pthread_mutex_unlock ( _m ); }
0
#include <pthread.h> void * thread_inc(void * arg); void * thread_des(void * arg); long long num = 0; pthread_mutex_t mutex; int main(int argc, char * argv[]) { pthread_t thread_id[100]; int i; pthread_mutex_init(&mutex, 0); for(i=0; i<100; i++) { if(i%2) pthread_create(&(thread_id[i]), 0, thread_inc, 0); else pthread_create(&(thread_id[i]), 0, thread_des, 0); } for(i=0; i<100; ++i) pthread_join(thread_id[i], 0); printf("result : %lld\\n", num); pthread_mutex_destroy(&mutex); return 0; } void * thread_inc(void * arg) { int i; for(i=0; i<50000000; ++i) { pthread_mutex_lock(&mutex); num += 1; pthread_mutex_unlock(&mutex); } return 0; } void * thread_des(void * arg) { int i; for(i=0; i<50000000; ++i) { pthread_mutex_lock(&mutex); num -= 1; pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char* argv[]) { struct Seatmap* map = (struct Seatmap*)malloc(sizeof(struct Seatmap)); initialize_seatmap(map); map->mutex = &mutex; map->cond = &cond; time_t t; const int NUM_BUYERS = atoi(argv[1]); srand((unsigned) time(&t)); struct Buyer* buyers[10][NUM_BUYERS]; struct BuyerQueue* bqs[10]; struct Seller* sellers[10]; for(int i = 0; i < 10;i++) { int ordinal; char priority; if(i == 0) { priority = 'H'; ordinal = 1; }else if(i < 4) { priority = 'M'; ordinal = i; }else{ priority = 'L'; ordinal = i -3; } char seller_name[4] = ""; seller_name[0] = priority; char cord[2]; sprintf(cord,"%d",ordinal); strcat(seller_name,cord); for(int j=0;j<NUM_BUYERS;j++) { int arrival_time = (int) rand() % 60; buyers[i][j] = createBuyer(priority, seller_name, j, arrival_time); } void* curr = buyers[i]; bqs[i] = init_BuyerQueue(curr, NUM_BUYERS); printBuyerQueue(bqs[i]); sellers[i] = createSeller(priority, ordinal, bqs[i], map); }; print_seatmap(map); pthread_t tids[10]; for(int i = 0; i < 10; i++) { struct Seller* next = sellers[i]; pthread_t cur; pthread_create(&cur, 0, sell, next); tids[i] = cur; } sleep(2); wakeup_all_seller_threads(); for (int i = 0 ; i < 10 ; i++) { pthread_t cur = tids[i]; pthread_join(cur, 0); } print_seatmap(map); for(int i = 0;i < 10;i++) { struct Seller* s = sellers[i]; printf("Report for seller %s:\\n", s->name); printf("Seller %s has %d customers who did not get tickets.\\n",s->name, s->q->count); printf("Seller %s has %d customers who got tickets.\\n",s->name, s->q->head); } printf("exiting\\n"); fflush(stdout); return(0); } void wakeup_all_seller_threads() { printf("waking up seller threads\\n"); fflush(stdout); pthread_mutex_lock(&mutex); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> static int files[128]; static unsigned int references[128]; static unsigned int oflag_busy_locks[128]; static pthread_mutex_t muteces[128]; static pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER; static int isInit = 0; static int oflag = O_RDONLY; static int change_oflag(int cpu); int init_msr(int init_oflag) { int i; int fd; const char* msr_file_name = "/dev/cpu/0/msr"; pthread_mutex_lock(&global_lock); if (!isInit) { memset(references,0,128*sizeof(unsigned int)); memset(oflag_busy_locks,0,128*sizeof(unsigned int)); for(i=0;i<128;i++) { pthread_mutex_init(&muteces[i], 0); } isInit = 1; } fd = open(msr_file_name, init_oflag); if (fd < 0) { fprintf(stderr, "ERROR\\n"); fprintf(stderr, "rdmsr: failed to open '%s': %s!\\n",msr_file_name , strerror(errno)); fprintf(stderr, " Please check if the msr module is loaded and the device file has correct permissions.\\n\\n"); pthread_mutex_unlock(&global_lock); return fd; } close(fd); if (oflag == O_RDONLY && init_oflag == O_RDWR) { oflag = init_oflag; for (i=0; i<128; i++) { int ret = change_oflag(i); if (ret) { pthread_mutex_unlock(&global_lock); return ret; } } } pthread_mutex_unlock(&global_lock); return 0; } static int change_oflag(int cpu) { pthread_mutex_lock(&muteces[cpu]); oflag_busy_locks[cpu] = 1; if (references[cpu] != 0) { char* msr_file_name = (char*) alloca(20 * sizeof(char)); sprintf(msr_file_name,"/dev/cpu/%d/msr",cpu); close(files[cpu]); files[cpu] = open(msr_file_name, oflag); if (files[cpu] < 0) { pthread_mutex_unlock(&muteces[cpu]); return files[cpu]; } } oflag_busy_locks[cpu] = 0; pthread_mutex_unlock(&muteces[cpu]); return 0; } int open_msr(uint32_t cpu, uint32_t msr, struct msr_handle * handle) { pthread_mutex_lock(&muteces[cpu]); if (references[cpu] == 0) { char* msr_file_name = (char*) alloca(20 * sizeof(char)); sprintf(msr_file_name,"/dev/cpu/%d/msr",cpu); files[cpu] = open(msr_file_name, oflag); if (files[cpu] < 0) { pthread_mutex_unlock(&muteces[cpu]); return files[cpu]; } } handle->cpu=cpu; handle->msr=msr; references[cpu]++; pthread_mutex_unlock(&muteces[cpu]); return 0; } int read_msr(struct msr_handle * handle) { uint32_t cpu = handle->cpu; if (pread(files[cpu], &handle->data, sizeof(uint64_t), handle->msr) != sizeof(uint64_t)) { if (errno == EBADF && references[cpu]) { while (oflag_busy_locks[cpu]) ; return read_msr(handle); } else { fprintf(stderr,"Error reading cpu %d reg %x\\n",cpu, handle->msr); return errno; } } return 0; } int write_msr(struct msr_handle handle) { uint32_t cpu = handle.cpu; if (pwrite(files[cpu], &handle.data, sizeof(uint64_t), handle.msr) != sizeof(uint64_t)) { if (errno == EBADF && oflag == O_RDWR && references[cpu]) { while (oflag_busy_locks[cpu]) ; return write_msr(handle); } else { fprintf(stderr,"Error writing cpu %d reg %x\\n",cpu, handle.msr); return errno; } } return 0; } void close_msr(struct msr_handle handle) { pthread_mutex_lock(&muteces[handle.cpu]); references[handle.cpu]--; if (references[handle.cpu] == 0) { close(files[handle.cpu]); } pthread_mutex_unlock(&muteces[handle.cpu]); }
1
#include <pthread.h> long totalSum = 0; int* arr; int size; int subSize; int index; unsigned int step; } args; int* initializeArray(unsigned int size, unsigned int mode) { int *arr = malloc(sizeof(int) * size); int i,j; if(mode == 0) { for(i = 0; i < size; i++) { arr[i] = i; } } else if(mode == 1) { for(j = 0; j < size; j++) { arr[j] = rand()%2001-1000; } } return arr; } pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void* sumBlocks(void * x) { long j = 0; struct args * block = (struct args *) x; int k = 0; unsigned long sum = 0; for(j = block->index;(j < block->size) && (j < (block->subSize+block->index)); j++){ sum = sum + block->arr[j]; printf("arr[j] j %d %d\\n", j,block->arr[j]); } pthread_mutex_lock(&mutex1); printf("Sum: %d\\n",sum); totalSum = totalSum + sum; printf("Total sum: %d\\n",totalSum); pthread_mutex_unlock(&mutex1); } double sumArray(int* array, unsigned int size, long* sum, unsigned int numBlocks, unsigned int step) { int subSize; subSize = size/numBlocks; double elapsed; struct timespec start, stop; clock_gettime(CLOCK_REALTIME, &start); struct args thread_args[numBlocks+1]; pthread_t threads[numBlocks+1]; int rc,counter = 0; int index = 0; for(counter = 0; counter < numBlocks+1; counter++,index +=subSize) { thread_args[counter].arr = array; thread_args[counter].size = size; thread_args[counter].subSize = subSize; thread_args[counter].index = index; thread_args[counter].step = step; rc = pthread_create(&threads[counter],0,sumBlocks,(void *)&thread_args[counter]); } for(counter = 0; counter < numBlocks; counter++) { pthread_join(threads[counter],0); } clock_gettime(CLOCK_REALTIME, &stop); elapsed = ((double)stop.tv_sec - (double)start.tv_sec)*1000 + ((double)stop.tv_nsec - (double)start.tv_nsec)/1000000; return elapsed; } double sumArrayRandom(int* array, unsigned int size, int* sum) { int i; double elapsed; struct timespec start, stop; clock_gettime(CLOCK_REALTIME, &start); for(i = 0; i < size; i++) { *sum = *sum + array[rand()%size]; } clock_gettime(CLOCK_REALTIME, &stop); elapsed = ((double)stop.tv_sec - (double)start.tv_sec)*1000 + ((double)stop.tv_nsec - (double)start.tv_nsec)/1000000; return elapsed; } bool isNumber(char *input) { int c = 0; for (c = 0; input[c] != '\\0'; c++){ if (isalpha(input[c])) { return 0; } } return 1; } int main(int argc, char *argv[]) { int size = 10000; int mode = 0; int blocks = 1; int steps = 1; int i = 0; while(i < argc) { if(strcmp(argv[i],"-s") == 0) { if(argv[i+1] == 0) { printf("No argument after -s. Reset to default size %d.\\n",10000); } else if(!isNumber(argv[i+1])) { printf("Not a number. Reset to default size %d.\\n",10000); } else if(atoi(argv[i+1]) < 0) { printf("Negative number not allowed. Reset to default size %d.\\n",10000); } else { size = atoi(argv[++i]); } } else if(strcmp(argv[i],"-m") == 0) { if(argv[i+1] == 0) { printf("No argument after -m. Reset to default mode %d.\\n",mode); } else if(!isNumber(argv[i+1])) { printf("Not a number. Reset to default mode %d.\\n",mode); } else if(atoi(argv[i+1]) != 0 && atoi(argv[i+1]) != 1) { printf("Not legal value of mode.\\n"); exit(-1); } else { mode = atoi(argv[++i]); } } else if(strcmp(argv[i],"-b") == 0) { if(argv[i+1] == 0) { printf("No argument after -b. Reset to default blocks %d.\\n",blocks); } else if(!isNumber(argv[i+1])) { printf("Not a number. Reset to default blocks %d.\\n",blocks); } else if(atoi(argv[i+1]) < 0) { printf("Negative number of blocks is not allowed.\\n"); exit(-1); } else { blocks = atoi(argv[++i]); } } else if(strcmp(argv[i],"-p") == 0) { if(argv[i+1] == 0) { printf("No argument after -p. Reset to default steps %d.\\n",steps); } else if(!isNumber(argv[i+1])) { printf("Not a number. Reset to default steps %d.\\n",steps); } else if(atoi(argv[i+1]) < 0) { printf("Negative number of steps is not allowed.\\n"); exit(-1); } else { steps = atoi(argv[++i]); } } else if(strcmp(argv[i],"-r") == 0) { if(argv[i+1] == 0) { printf("No argument after -r. No random seed generated.\\n"); } else if(!isNumber(argv[i+1])) { printf("Not a number for random seed\\n"); } else { srand(atoi(argv[++i])); } } i++; } int* arr = initializeArray(size,mode); long s1; int s2; double time1 = sumArray(arr,size,&s1,blocks,steps); double time2 = sumArrayRandom(arr,size,&s2); printf("blocks: %d\\n",blocks); printf("size: %d\\n",size); printf("steps: %d\\n",steps); printf("mode: %d\\n",mode); printf("Total sum is %d\\n",totalSum); printf("Total time for computation of sumArray is %f milliseconds\\n",time1); printf("Total time for computation of sumArrayRandom is %f milliseconds\\n",time2); return (0); }
0
#include <pthread.h> int thread_flag; pthread_cond_t thread_flag_cv = PTHREAD_COND_INITIALIZER; pthread_mutex_t thread_flag_mutex = PTHREAD_MUTEX_INITIALIZER; struct job { struct job* next; int num; }; struct job* job_queue; struct job* tail; void initialize_flag () { thread_flag = 0; printf("thread_flag: %d\\n", thread_flag); } void set_thread_flag (int flag_value) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_cond_signal (&thread_flag_cv); pthread_mutex_unlock (&thread_flag_mutex); } void print_list(struct job * job_list){ int i; i=1; struct job* aux = job_queue; while(aux != 0){ printf("%d) %d\\n",i,aux->num); aux = aux->next; i++; } printf("Terminó la lista.\\n\\n"); } void init_list (int list_lentgh){ int i, n; srand(time(0)); struct job* aux = job_queue; for(i = 0; i < list_lentgh; i++){ n = rand()%100; aux->num = n; tail = 0; tail = (struct job *) malloc(sizeof (struct job)); pthread_mutex_lock (&thread_flag_mutex); aux->next = tail; aux = aux->next; pthread_mutex_unlock (&thread_flag_mutex); } set_thread_flag(1); } char* is_prime(int a){ int c; for ( c = 2 ; c <= a - 1 ; c++ ) if ( a%c == 0 ) return "No"; if ( c == a ) return "Si"; return 0; } int process_job(struct job* job_obj, int option){ switch(option){ case 1: printf("La raiz cuadrada de %d es: %.3f\\n",job_obj->num, sqrt(job_obj->num));break; case 2: printf("El logaritmo natural de %d es: %.3f\\n",job_obj->num, log(job_obj->num));break; case 3: printf("%d es un numero primo? %s\\n", job_obj->num, is_prime(job_obj->num));break; } return 0; } int do_work(int n){ set_thread_flag(0); printf("trabajo del hilo %d\\n\\n", n); sleep(1); set_thread_flag(1); return 0; } void* thread_function (void* arg){ int* n = (int *) arg; printf("thread_flag before while: %d (hilo %d)\\n", thread_flag, *n); while (1) { pthread_mutex_lock (&thread_flag_mutex); while (!thread_flag){ pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); printf("hilo %d esperando...\\n", *n); } pthread_mutex_unlock (&thread_flag_mutex); printf("Hilo %d ejecutando\\n", *n); do_work (*n); } return (void*) 1; } int main(){ printf("Iniciando...\\n"); job_queue = 0; job_queue = (struct job *) malloc(sizeof (struct job)); initialize_flag(); init_list(9); print_list(job_queue); pthread_t thread1_id; pthread_t thread2_id; pthread_t thread3_id; int* num; num = 0; num = (int *) malloc(sizeof (int)); *num = 1; pthread_create (&thread1_id, 0, &thread_function, num); int* num2; num2 = 0; num2 = (int *) malloc(sizeof (int)); *num2 = 2; pthread_create (&thread2_id, 0, &thread_function, num2); int* num3; num3 = 0; num3 = (int *) malloc(sizeof (int)); *num3 = 3; pthread_create (&thread3_id, 0, &thread_function, num3); void * status1; void * status2; void * status3; pthread_join (thread1_id, &status1); pthread_join (thread2_id, &status2); pthread_join (thread3_id, &status3); free(num); free(num2); free(num3); printf("FInal thread_flag: %d\\n", thread_flag); return 0; }
1
#include <pthread.h> void monitor_cross(struct cart_t* cart) { pthread_mutex_lock(&gl_monLock); if (gl_direction == '\\0') gl_direction = cart->dir; else { switch (cart->dir) { fprintf(stderr, "[Cart]\\tCart %i from direction %c must wait before entering intersection\\n", cart->num, cart->dir); case Q_NORTH: pthread_cond_wait(&gl_northCond, &gl_monLock); break; case Q_SOUTH: pthread_cond_wait(&gl_southCond, &gl_monLock); break; case Q_EAST: pthread_cond_wait(&gl_eastCond, &gl_monLock); break; case Q_WEST: pthread_cond_wait(&gl_westCond, &gl_monLock); break; } } fprintf(stderr, "[Cart]\\tCart %i from direction %c allowed to proceed into intersection\\n", cart->num, cart->dir); q_cartHasEntered(gl_direction); pthread_mutex_unlock(&gl_monLock); sleep(10); pthread_mutex_lock(&gl_monLock); fprintf(stderr, "[Cart]\\tCart %i from direction %c crosses intersection\\n", cart->num, cart->dir); pthread_mutex_unlock(&gl_monLock); }
0
#include <pthread.h> void *sum(void *p); double *v1, *v2; double sumtotal = 0.0; int numthreads, n; pthread_mutex_t mutex; int main(int argc, char **argv) { pthread_t tid[8]; int i, myid[8]; struct timeval start, end; gettimeofday(&start, 0); pthread_mutex_init(&mutex, 0); scanf("%d %d", &n, &numthreads); v1 = (double *) malloc(n * sizeof (double)); v2 = (double *) malloc(n * sizeof (double)); for (i = 0; i < n; i++) { v1[i] = 1; v2[i] = 2; } for (i = 0; i < numthreads; i++) { myid[i] = i; pthread_create(&tid[i], 0, sum, &myid[i]); } for (i = 0; i < numthreads; i++) { pthread_join(tid[i], 0); } free(v1); free(v2); pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); long spent = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec); printf("%.0f\\n%ld\\n", sumtotal, spent); return 0; } void *sum(void *p) { int myid = *((int *) p); int start = (myid * (long long) n) / numthreads; int end = ((myid + 1) * (long long) n) / numthreads; int i, k = myid, m = 1, len; double sum = 0.0; len = end - start; for (i = 0; i < len / 64; i++) { for (k = 0; k < 64; k++) { m = start + (i * 64 + k); sum += v1[m] * v2[m]; } } if ((len / 64) * 64 != len) { for (m = start + (len / 64) * 64; m < end; m++) { sum += v1[m] * v2[m]; } } pthread_mutex_lock(&mutex); sumtotal += sum; pthread_mutex_unlock(&mutex); return 0; }
1
#include <pthread.h> int SERVER_SHUT_DOWN; pthread_mutex_t sd_lock; pthread_t sd_thread; void* shut_down(void* p) { pthread_mutex_init(&sd_lock,0); pthread_mutex_lock(&sd_lock); SERVER_SHUT_DOWN = 0; pthread_mutex_unlock(&sd_lock); static struct termios oldt, newt; tcgetattr( STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON); tcsetattr( STDIN_FILENO, TCSANOW, &newt); while (getchar() !='q'); pthread_mutex_lock(&sd_lock); SERVER_SHUT_DOWN = 1; pthread_mutex_unlock(&sd_lock); fprintf(stdout, "\\nServer start shut down\\n"); tcsetattr( STDIN_FILENO, TCSANOW, &oldt); return 0; } int shut_down_thread_init() { pthread_create(&sd_thread,0,&shut_down,0); return 0; } int shut_down_thread_join() { pthread_join(sd_thread,0); return 0; } int is_shut_down() { pthread_mutex_lock(&sd_lock); int res = SERVER_SHUT_DOWN; pthread_mutex_unlock(&sd_lock); return res; }
0
#include <pthread.h> pthread_t threads[4]; int thread_count; pthread_mutex_t thread_count_mutex; pthread_cond_t thread_count_condvar; sig_atomic_t sigabrt_received; void incr_thread_count (void) { pthread_mutex_lock (&thread_count_mutex); ++thread_count; if (thread_count == 4) pthread_cond_signal (&thread_count_condvar); pthread_mutex_unlock (&thread_count_mutex); } void cond_wait (pthread_cond_t *cond, pthread_mutex_t *mut) { pthread_mutex_lock (mut); pthread_cond_wait (cond, mut); pthread_mutex_unlock (mut); } void noreturn (void) { pthread_mutex_t mut; pthread_cond_t cond; pthread_mutex_init (&mut, 0); pthread_cond_init (&cond, 0); cond_wait (&cond, &mut); } void * thread_entry (void *unused) { incr_thread_count (); noreturn (); } void sigabrt_handler (int signo) { sigabrt_received = 1; } void hand_call_with_signal (void) { const struct timespec ts = { 0, 10000000 }; sigabrt_received = 0; pthread_kill (threads[0], SIGABRT); while (! sigabrt_received) nanosleep (&ts, 0); } void wait_all_threads_running (void) { pthread_mutex_lock (&thread_count_mutex); if (thread_count == 4) { pthread_mutex_unlock (&thread_count_mutex); return; } pthread_cond_wait (&thread_count_condvar, &thread_count_mutex); if (thread_count == 4) { pthread_mutex_unlock (&thread_count_mutex); return; } pthread_mutex_unlock (&thread_count_mutex); printf ("failed waiting for all threads to start\\n"); abort (); } void all_threads_running (void) { } int main (void) { int i; signal (SIGABRT, sigabrt_handler); pthread_mutex_init (&thread_count_mutex, 0); pthread_cond_init (&thread_count_condvar, 0); for (i = 0; i < 4; ++i) pthread_create (&threads[i], 0, thread_entry, 0); wait_all_threads_running (); all_threads_running (); return 0; }
1
#include <pthread.h> int num_threads = 1; int keys[100000]; pthread_mutex_t lock; int key; int val; struct _bucket_entry *next; } bucket_entry; bucket_entry *table[5]; void panic(char *msg) { printf("%s\\n", msg); exit(1); } double now() { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + tv.tv_usec / 1000000.0; } void insert(int key, int val) { int i = key % 5; if(i == key % 5) { pthread_mutex_lock(&lock); } else { pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); } bucket_entry *e = (bucket_entry *) malloc(sizeof(bucket_entry)); if (!e) panic("No memory to allocate bucket!"); e->next = table[i]; e->key = key; e->val = val; table[i] = e; pthread_mutex_unlock(&lock); } bucket_entry * retrieve(int key) { bucket_entry *b; for (b = table[key % 5]; b != 0; b = b->next) { if (b->key == key) { return b; } } return 0; } void * put_phase(void *arg) { long tid = (long) arg; int key = 0; for (key = tid ; key < 100000; key += num_threads) { insert(keys[key], tid); } pthread_exit(0); } void * get_phase(void *arg) { long tid = (long) arg; int key = 0; long lost = 0; for (key = tid ; key < 100000; key += num_threads) { if (retrieve(keys[key]) == 0) { lost++; } } printf("[thread %ld] %ld keys lost!\\n", tid, lost); pthread_exit((void *)lost); } int main(int argc, char **argv) { long i; pthread_t *threads; pthread_mutex_init(&lock, 0); double start, end; if (argc != 2) { panic("usage: ./parallel_hashtable <num_threads>"); } if ((num_threads = atoi(argv[1])) <= 0) { panic("must enter a valid number of threads to run"); } srandom(time(0)); for (i = 0; i < 100000; i++) keys[i] = random(); threads = (pthread_t *) malloc(sizeof(pthread_t)*num_threads); if (!threads) { panic("out of memory allocating thread handles"); } start = now(); for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], 0, put_phase, (void *)i); } for (i = 0; i < num_threads; i++) { pthread_join(threads[i], 0); } end = now(); printf("[main] Inserted %d keys in %f seconds\\n", 100000, end - start); memset(threads, 0, sizeof(pthread_t)*num_threads); start = now(); for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], 0, get_phase, (void *)i); } long total_lost = 0; long *lost_keys = (long *) malloc(sizeof(long) * num_threads); for (i = 0; i < num_threads; i++) { pthread_join(threads[i], (void **)&lost_keys[i]); total_lost += lost_keys[i]; } end = now(); printf("[main] Retrieved %ld/%d keys in %f seconds\\n", 100000 - total_lost, 100000, end - start); return 0; }
0
#include <pthread.h> int finish = 0; pthread_rwlock_t finish_lock = PTHREAD_RWLOCK_INITIALIZER; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; struct job { struct job *j_prev; struct job *j_next; pthread_t j_id; int data; }; struct job_queue { pthread_rwlock_t q_lock; struct job *q_head; struct job *q_tail; }; int queue_init(struct job_queue *qp) { int err; qp->q_head = 0; qp->q_tail = 0; err = pthread_rwlock_init(&qp->q_lock, 0); if(err != 0) { return err; } return 0; } void job_insert(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); if(qp->q_tail == 0) { q_head = jp; } else { q_tail->j_next = jp; } qp->q_tail = jp; pthread_rwlock_unlock(&qp->q_lock); if(qp->q_head == qp->q_tail) { pthread_mutex_lock(&qlock); pthread_cond_signal(&qready); pthread_mutex_unlock(&qlock); } } void job_remove(struct queue *qp, struct job *jp) { } void worker(void *arg); void master(void *arg); int main(int argc, char const *argv[]) { pthread_t master_id, worker_id; pthread_create(&master_id, 0, master, 0); pthread_create(&worker_id, 0, worker, 0); pthread_join(master_id, 0); return 0; } void worker(void *arg) { } void master(void *arg) { }
1
#include <pthread.h> char depot[15]; volatile size_t stock; pthread_mutex_t mute = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_full = PTHREAD_COND_INITIALIZER; pthread_cond_t c_empty = PTHREAD_COND_INITIALIZER; void show_depot(char* str) { int i = 0; printf("\\r"); for(; i<stock; i++) { printf("%c ",depot[i]); } printf("%s",str); fflush(stdout); } void* in_func_pro(void* arg) { for(;;) { pthread_mutex_lock(&mute); if(stock >= 15) { pthread_cond_wait(&c_full,&mute); } depot[stock++] = 'A' + rand() % 26; show_depot("->"); usleep(rand()%100*1000); pthread_cond_signal(&c_empty); pthread_mutex_unlock(&mute); } } void* in_func_use(void* arg) { for(;;) { pthread_mutex_lock(&mute); if(stock <= 0) { pthread_cond_wait(&c_empty,&mute); } stock--; show_depot("<-"); usleep(rand()%100*500); sleep(1); pthread_cond_signal(&c_full); pthread_mutex_unlock(&mute); } } int main() { srand(time(0)); pthread_t pth_id1,pth_id2; pthread_create(&pth_id1,0,in_func_pro,0); pthread_create(&pth_id2,0,in_func_use,0); pthread_detach(pth_id1); pthread_detach(pth_id2); scanf("%*c"); }
0
#include <pthread.h> struct node { struct node* next; int value; }; struct node * file_lock = 0; struct node * volatile file_lock_free = 0; pthread_mutex_t file_mutex; void push_lock(int value_to_push) { struct node * new_node; new_node= malloc(sizeof(struct node)); new_node-> value=value_to_push; pthread_mutex_lock(&file_mutex); new_node-> next= file_lock; file_lock= new_node; pthread_mutex_unlock(&file_mutex); } int pop_lock() { pthread_mutex_lock(&file_mutex); int valeur_retiree= file_lock-> value; struct node* node_a_supprimer= file_lock; file_lock=file_lock -> next; pthread_mutex_unlock(&file_mutex); free(node_a_supprimer); return valeur_retiree; } void push_lock_free(int value_to_push) { struct node * new_node; new_node= malloc(sizeof(struct node)); new_node-> value=value_to_push; do { new_node-> next= file_lock_free; } while (! __sync_bool_compare_and_swap(&file_lock_free, new_node -> next, new_node)); } int pop_lock_free() { struct node* node_a_supprimer; do { node_a_supprimer= file_lock_free; } while(! __sync_bool_compare_and_swap(&file_lock_free, node_a_supprimer, node_a_supprimer -> next)); int valeur_retiree = node_a_supprimer->value; free(node_a_supprimer); return valeur_retiree; } void * thread_start(void * arg) { printf("Hello World\\n"); for (int i=0; i<1000;++i) { push_lock_free(i); } for (int i = 0; i < 1000; ++i) { pop_lock_free(); } return 0; } int main() { pthread_mutex_init(&file_mutex, 0); pthread_t new_thread[10]; for (int i=0; i<10; ++i){ pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&(new_thread[i]), &attr, &thread_start, 0); } for (int i=0; i<10; ++i){ pthread_join(new_thread[i], (void**) 0); } pthread_mutex_destroy(&file_mutex); return 0; }
1
#include <pthread.h> { int valid; unsigned int session; unsigned int pathid; unsigned int energy; int done; } p_ent; int pcount = 0; int idle_uW=0; p_ent __paths[10]; int64_t __battery_energy=0; int64_t __battery_capacity=0; unsigned int __path_costs[NUMPATHS]; unsigned int __path_count[NUMPATHS]; unsigned int __path_pred_count[NUMPATHS][NUMSTATES]; pthread_mutex_t __p_mutex = PTHREAD_MUTEX_INITIALIZER; int count_since_eval=0; void plock() { pthread_mutex_lock(&__p_mutex); } void punlock() { pthread_mutex_unlock(&__p_mutex); } int doewma(int oldv, int newv, int num, int den) { int retval; retval = ((oldv * (den-num)) + (newv * num))/den; return retval; } int doeval() { energy_evaluation_struct_t * eval; plock(); eval = reevaluate_energy_level(__battery_energy,__battery_capacity); curstate = eval->energy_state; curgrade = eval->state_grade; free(eval); punlock(); } void energy_callback(int uJin, int uJout, unsigned int battery) { int idle_share; int p_share; int p_ind; int i; plock(); __battery_energy = battery; if (pcount == 0) { idle_share =uJout; } else { idle_share = idle_uW*ENERGY_TIME; if (idle_share > uJout) { idle_share = uJout; p_share = 0; } else { p_share = uJout - idle_share; } } p_ind = (p_share / pcount)+1; idle_uW = doewma(idle_uW, idle_share/ENERGY_TIME, 3,10); for (i=0; i < 10; i++) { if (__paths[i].valid) { __paths[i].energy += p_ind; if (__paths[i].done) { __path_costs[__paths[i].pathid] = doewma(__path_costs[__paths[i].pathid], __paths[i].energy, 3,10); __paths[i].valid = 0; } } } count_since_eval++; punlock(); if (count_since_eval > EVAL_COUNT) { doeval(); } } void start_path(unsigned int session) { int i; plock(); for (i=0; i < 10; i++) { if (__paths[i].valid==0) { __paths[i].valid = 1; __paths[i].session = session; __paths[i].energy=0; __paths[i].done = 0; __paths[i].pathid=0; break; } } punlock(); } void end_path(unsigned int session, unsigned int pathid) { int i; plock(); __path_count[pathid]++; for (i=0; i < 10; i++) { if (__paths[i].valid==1 && __paths[i].session==session) { __paths[i].done = 1; __paths[i].pathid=pathid; break; } } punlock(); } void start_energy_mgr() { set_energy_callback(energy_callback); __battery_capacity = get_battery_size(); }
0
#include <pthread.h> int value; pthread_cond_t rc, wc; pthread_mutex_t rm, wm; int r_wait, w_wait; }Storage; void setValue(Storage *s, int value) { s->value = value; } int getValue(Storage *s) { return s->value; } void *set_thread(void *arg) { Storage *s = (Storage *)arg; for (int i = 0; i < 100; ++i) { setValue(s, i + 100); printf("(0x%lx) set data:%d\\n",pthread_self(), i); pthread_mutex_lock(&s->rm); while (!s->r_wait) { pthread_mutex_unlock(&s->rm); sleep(1); pthread_mutex_lock(&s->rm); } s->r_wait = 0; pthread_mutex_unlock(&s->rm); pthread_cond_broadcast(&s->rc); pthread_mutex_lock(&s->wm); s->w_wait = 1; pthread_cond_wait(&s->wc, &s->wm); pthread_mutex_unlock(&s->wm); } return (void *)0; } void *get_thread(void *arg) { Storage *s = (Storage *)arg; for (int i = 0; i < 100; ++i) { pthread_mutex_lock(&s->rm); s->r_wait = 1; pthread_cond_wait(&s->rc, &s->rm); pthread_mutex_unlock(&s->rm); int value = getValue(s); printf("(0x%lx) get data:%d\\n",pthread_self(), value); pthread_mutex_lock(&s->wm); while (!s->w_wait) { pthread_mutex_unlock(&s->wm); sleep(1); pthread_mutex_lock(&s->wm); } s->w_wait = 0; pthread_mutex_unlock(&s->wm); pthread_cond_broadcast(&s->wc); } return (void *)0; } int main () { int err; pthread_t rth, wth; Storage s; s.r_wait = 0; s.w_wait = 0; pthread_mutex_init(&s.rm, 0); pthread_mutex_init(&s.wm, 0); pthread_cond_init(&s.rc, 0); pthread_cond_init(&s.wc, 0); if ((err = pthread_create(&rth, 0, set_thread, (void *)&s)) != 0) { perror("thread create error!"); } if ((err = pthread_create(&wth, 0, get_thread, (void *)&s)) != 0) { perror("thread create error!"); } pthread_join(rth, 0); pthread_join(wth, 0); pthread_mutex_destroy(&s.rm); pthread_mutex_destroy(&s.wm); pthread_cond_destroy(&s.rc); pthread_cond_destroy(&s.wc); return 0; }
1
#include <pthread.h> char **P; pthread_mutex_t m; pthread_cond_t cond; } Est; Est *E = 0; void myInit(){ if(E == 0){ E = (Est*)malloc(sizeof(Est)); pthread_mutex_init(&E->m, 0); pthread_cond_init(&E->cond, 0); E->P = (char**)malloc(5*sizeof(char*)); } } int ubicar(char *nom, int k){ myInit(); int f = -1; int c = 0; for(int i=0; i<5; i++){ if(E->P[i]==0){ c++; if(c==k){ f=i+1-c; return f; } } else { c=0; f=-1; } } return f; } int reservar(char *nom, int k){ myInit(); pthread_mutex_lock(&E->m); int p = ubicar(nom,k); while((p = ubicar(nom,k)) == -1){ pthread_cond_wait(&E->cond,&E->m); } for(int i = 0; i<k;i++){ E->P[p+i] = (char*)malloc(strlen(nom)+1); strcpy(E->P[p+i], nom); } pthread_cond_broadcast(&E->cond); pthread_mutex_unlock(&E->m); return p; } void liberar(char *nom){ pthread_mutex_lock(&E->m); for(int i=0; i<5;i++){ if(E->P[i] != 0){ if(strcmp(E->P[i],nom)==0){ free(E->P[i]); E->P[i] = 0; } } } pthread_cond_broadcast(&E->cond); pthread_mutex_unlock(&E->m); } void printE(){ for(int i=0;i<5;i++){ printf("[%s]",E->P[i]); } printf("\\n"); } int main(int argc, char *argv[]){ E = (Est*)malloc(sizeof(Est)); pthread_mutex_init(&E->m, 0); pthread_cond_init(&E->cond, 0); E->P = (char**)malloc(5*sizeof(char*)); printE(); int a = reservar("nom",3); printf("%d\\n",a); printE(); a = reservar("nom2",2); printf("%d\\n",a); printE(); liberar("nom"); printf("EndFREE\\n"); printE(); a = reservar("nom3",1); printf("%d\\n",a); printE(); a = reservar("nom4",1); printf("%d\\n",a); printE(); a = reservar("nom5",1); printf("%d\\n",a); printE(); }
0
#include <pthread.h> void* func_1(void *ptr); void* func_2(void *ptr); void* func_3(void *ptr); int a = 0; pthread_mutex_t lock; int main(int argc, char *argv[]) { system("clear"); pthread_t thd1, thd2; int t1, t2; char *mesg1 = "I'm Thread 1"; char *mesg2 = "I'm Thread 2"; t1 = pthread_create(&thd1, 0, *func_1, (void *) mesg1); t2 = pthread_create(&thd2, 0, *func_2, (void *) mesg2); pthread_join(thd1, 0); pthread_join(thd2, 0); return 0; } void * func_1(void *ptr) { int i; for(i =0; a < 100; i++){ if (a % 2 == 0) { pthread_mutex_lock(&lock); a = a + 1; printf("thead 1: %d\\t\\n", a); pthread_mutex_unlock(&lock); } usleep(1); } } void * func_2(void *ptr) { int i; for(i =0; a < 100; i++){ if (a % 2 == 1) { pthread_mutex_lock(&lock); a = a + 1; printf("thread 2: %d\\t\\n", a); pthread_mutex_unlock(&lock); } usleep(1); } }
1
#include <pthread.h> pthread_mutex_t mu; pthread_cond_t registerSignal; int toTreat = 0, nTreated = 0, size = 0; int *treatTimes; FILE *outputF; void fileOP(const char* inputFile, const char* outputFile) { int num, i; FILE* file = fopen(inputFile, "r"); while (!feof(file)) { fscanf(file, "%d", &num); size++; } fclose(file); treatTimes = (int*) malloc(size * sizeof(int)); file = fopen(inputFile, "r"); for (i = 0; i < size; i++) { fscanf(file, "%d", &num); treatTimes[i] = num; } fclose(file); outputF = fopen(outputFile, "w"); } void* nurse(void *ptr) { int i; for (i = 0; i < size; i++) { pthread_mutex_lock(&mu); printf("Nurse: Patient %d registered \\n", i + 1); fprintf(outputF, "Nurse: Patient %d registered \\n", i + 1); toTreat++; pthread_cond_signal(&registerSignal); pthread_mutex_unlock(&mu); sleep(2); } pthread_cond_signal(&registerSignal); pthread_exit(0); } void* doctor(int dNo) { while (1) { pthread_mutex_lock(&mu); while (toTreat <= 0 && nTreated < size) { pthread_cond_wait(&registerSignal, &mu); } int tmp = nTreated; toTreat--; nTreated++; pthread_mutex_unlock(&mu); if (tmp < size) { sleep(treatTimes[tmp]); pthread_mutex_lock(&mu); printf("Doctor %d: Patient %d treated\\n", dNo, tmp + 1); fprintf(outputF, "Doctor %d: Patient %d treated\\n", dNo, tmp + 1); pthread_mutex_unlock(&mu); } if (nTreated >= size) break; } pthread_exit(0); } int main(int argc, char **argv) { pthread_t nurse_t, doc1_t, doc2_t; pthread_mutex_init(&mu, 0); pthread_cond_init(&registerSignal, 0); fileOP("numbers.txt", "output.txt"); pthread_create(&nurse_t, 0, nurse, 0); pthread_create(&doc1_t, 0, doctor, 1); pthread_create(&doc2_t, 0, doctor, 2); pthread_join(doc1_t, 0); pthread_join(doc2_t, 0); pthread_join(nurse_t, 0); pthread_mutex_destroy(&mu); pthread_cond_destroy(&registerSignal); free(treatTimes); fclose(outputF); return 0; }
0
#include <pthread.h> int event_handler_init(struct event_handler* eh) { do { eh->ev_cur = 0; eh->ev_end = 0; eh->ev_size = 0; eh->ev_max = MAX_EVENTS; eh->tr_busy = 0; eh->tr_min = MIN_THREADS; eh->tr_max = MAX_THREADS; eh->tr_live = eh->tr_min; eh->eh_cancel = 0; if ((eh->events = (struct event*)malloc(sizeof(struct event) * MAX_EVENTS)) == 0) break; if (pthread_mutex_init(&(eh->ev_lock), 0) || pthread_cond_init(&(eh->ev_cond), 0) || pthread_cond_init(&(eh->th_cond), 0)) break; for (int i = 0; i < MIN_THREADS; ++i) { pthread_t th; if (pthread_create(&th, 0, &event_thread, (void*) eh)) break; pthread_detach(th); } memset(eh->events, 0, sizeof(struct event) * MAX_EVENTS); return 0; } while (0); event_handler_destroy(eh); return -1; } int event_handler_add(struct event_handler* eh, struct event* ev) { if (!eh || !ev) return -1; if (eh->eh_cancel) return -2; if (__sync_fetch_and_add(&eh->ev_size, 0) > EVENTS_NUM) if (__sync_fetch_and_add(&eh->tr_live, 0) < eh->tr_max) event_handler_addth(eh, 1); pthread_mutex_lock(&(eh->ev_lock)); while (eh->ev_max <= eh->ev_size) { pthread_cond_wait(&(eh->th_cond), &(eh->ev_lock)); } eh->events[eh->ev_end].function = ev->function; eh->events[eh->ev_end].fd = ev->fd; eh->events[eh->ev_end].op = ev->op; eh->events[eh->ev_end].arg = ev->arg; eh->ev_end = (eh->ev_end + 1) % eh->ev_max; eh->ev_size = eh->ev_size + 1; pthread_mutex_unlock(&(eh->ev_lock)); pthread_cond_signal(&(eh->ev_cond)); return 0; } int event_handler_addth(struct event_handler* eh, int n) { int i; for (i = 0; i < n; ++i) { pthread_t th; if (pthread_create(&th, 0, event_thread, (void*)eh)) break; pthread_detach(th); __sync_fetch_and_add(&eh->tr_live, 1); } return i; } void* event_thread(void* event_hand) { struct timespec timetodie; timetodie.tv_nsec = 0; struct event_handler* eh = (struct event_handler*) event_hand; int timeup = 0; while (1) { pthread_cond_broadcast(&(eh->th_cond)); pthread_mutex_lock(&(eh->ev_lock)); timetodie.tv_sec = eh->now + LIVING_SEC; while (eh->ev_size == 0 && !eh->eh_cancel && !timeup) { if (pthread_cond_timedwait(&(eh->ev_cond), &(eh->ev_lock), &timetodie) == ETIMEDOUT) { if (__sync_fetch_and_add(&eh->tr_live, 0) > eh->tr_min) timeup = 1; } } if (timeup || eh->eh_cancel) { pthread_mutex_unlock(&(eh->ev_lock)); break; } struct event ev; ev.function = eh->events[eh->ev_cur].function; ev.fd = eh->events[eh->ev_cur].fd; ev.op = eh->events[eh->ev_cur].op; ev.arg = eh->events[eh->ev_cur].arg; eh->ev_cur = (eh->ev_cur + 1) % (eh->ev_max); eh->ev_size = eh->ev_size - 1; pthread_mutex_unlock(&(eh->ev_lock)); __sync_fetch_and_add(&eh->tr_busy, 1); (*ev.function)(ev.fd, ev.op, ev.arg); __sync_fetch_and_sub(&eh->tr_busy, 1); } __sync_fetch_and_sub(&eh->tr_live, 1); pthread_exit(0); } void event_handler_destroy(struct event_handler* eh) { if (!eh) return; eh->eh_cancel = 1; pthread_cond_broadcast(&(eh->ev_cond)); while (__sync_fetch_and_add(&eh->tr_live, 0)); if (eh->events) free(eh->events); pthread_mutex_destroy(&(eh->ev_lock)); pthread_cond_destroy(&(eh->ev_cond)); pthread_cond_destroy(&(eh->th_cond)); }
1
#include <pthread.h> void* wkr(void *arg) { int n, i, fd, got; long long k; char *ptr, *ptc, buf[WEBHDR]; uint64_t cd; struct qstat *tt = arg; struct epoll_event events[ECHUNK]; struct iovec iov = {.iov_base = buf, .iov_len = BHSIZE}; struct msghdr mh = { .msg_name = 0, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = 0, .msg_controllen = 0, .msg_flags = MSG_TRUNC}; for (; ;) { if ( (n = epoll_wait(tt->efd, events, ECHUNK, -1)) < 0) { perror("epoll_wait"); exit(1); } for (i = 0; i < n; i++) { cd = events[i].data.u64; fd = cd & 0xFFFFFFFF; cd >>= 32; if (cd) { while ( (got = syscall(SYS_recvmsg, fd, &mh, MSG_TRUNC)) < 0 && errno == EINTR); if (got < 0) { coe = errno; while (close(fd) < 0 && errno == EINTR); pthread_mutex_lock(&tt->mx); tt->cox++; pthread_mutex_unlock(&tt->mx); continue; } if (got == 0) { while (close(fd) < 0 && errno == EINTR); scf = 1; pthread_mutex_lock(&tt->mx); tt->cox++; pthread_mutex_unlock(&tt->mx); continue; } pthread_mutex_lock(&tt->mx); tt->bps += got; pthread_mutex_unlock(&tt->mx); if ((cd -= got) <= 0) { send_req(fd, tt); cd = 0; } } else { while ( (got = recv(fd, buf, WEBHDR - 1, 0)) < 0 && errno == EINTR); if (got < 0) { coe = errno; while (close(fd) < 0 && errno == EINTR); pthread_mutex_lock(&tt->mx); tt->cox++; pthread_mutex_unlock(&tt->mx); continue; } if (got == 0) { while (close(fd) < 0 && errno == EINTR); scf = 1; pthread_mutex_lock(&tt->mx); tt->cox++; pthread_mutex_unlock(&tt->mx); continue; } pthread_mutex_lock(&tt->mx); tt->bps += got; pthread_mutex_unlock(&tt->mx); buf[got] = '\\0'; if ( (ptr = strstr(buf, "\\r\\n\\r\\n")) == 0) { fputs("Bad response header:\\n", stderr); fputs(buf, stderr); exit(1); } *ptr = '\\0'; if ( (ptc = strstr(buf, "Content-Length")) != 0) { if (sscanf(ptc, "%*s %llu", &k) <= 0) { perror("sscanf"); fputs(strcat(ptc, "\\n"), stderr); exit(1); } cd = k - (&buf[got] - ptr - 4); if (cd >> 32) { fputs("HTTP object must not exceed 4.2GB\\n", stderr); exit(1); } } else { if (buf[9] == '2') { fputs("Content-Length header must be specified\\n", stderr); exit(1); } cd = 0; } if (cd <= 0) { send_req(fd, tt); cd = 0; } } events[i].data.u64 = (cd << 32) | fd; events[i].events = EPOLLIN; epoll_ctl(tt->efd, EPOLL_CTL_MOD, fd, &events[i]); } } }
0
#include <pthread.h> { int count; int *array; }arr_num; double shared_x; pthread_mutex_t lock_x; void swap(int* a, int* b) { int aux; aux = *a; *a = *b; *b = aux; } int divide(int *vec, int left, int right) { int i, j; i = left; for (j = left + 1; j <= right; ++j) { if (vec[j] < vec[left]) { ++i; swap(&vec[i], &vec[j]); } } swap(&vec[left], &vec[i]); return i; } void quickSort(int *vec, int left, int right) { int r; if (right > left) { r = divide(vec, left, right); quickSort(vec, left, r - 1); quickSort(vec, r + 1, right); } } void quick_sort (int *a, int n) { int i, j, p, t; if (n < 2) return; p = a[n / 2]; for (i = 0, j = n - 1;; i++, j--) { while (a[i] < p) i++; while (p < a[j]) j--; if (i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } quick_sort(a, i); quick_sort(a + i, n - i); } void* quick_sort_m (void* parameters) { struct arr_num* arr = (struct arr_num*) parameters; int i,j,p,t,th_num; pthread_t thread[25000]; if (arr->count < 2) return; p=arr->array[arr->count/2]; for(i = 0,j=arr->count-1;; i++,j++) { while(arr->array[i]<p) i++; while (p<arr->array[j]) j--; if (i >= j) break; t = arr->array[i]; arr->array[i] = arr->array[j]; arr->array[j] = t; } pthread_mutex_lock(&lock_x); th_num++; pthread_create (&thread[th_num], 0, &quick_sort_m,&arr); pthread_join (thread[th_num], 0); pthread_mutex_unlock(&lock_x); pthread_mutex_lock(&lock_x); th_num++; arr->array=arr->array+i; arr->count=arr->count-i; pthread_create (&thread[th_num], 0, &quick_sort_m,&arr); pthread_join (thread[th_num], 0); pthread_mutex_unlock(&lock_x); } int run_s(int num){ int a[num],i,n; n = sizeof a / sizeof a[0]; for (i=0;i<num;i++) a[i]=rand() % num + 1; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\\n" : " "); printf("\\n----------- sorted -----------\\n"); quick_sort(a, n); for (i = 0; i <= n; i++) printf("%d%s", a[i], i == n ? "\\n" : " "); return 0; } int run_m(int num){ struct arr_num an; int r,j; pthread_t thread[25000]; pthread_mutex_init(&lock_x, 0); an.count=num; an.array= malloc(sizeof(int) * an.count); for (r=0;r<an.count;r++) { an.array[r]=rand() % num - 1; printf(" -- %d - %d -- \\n",r,an.array[r]); } pthread_create (&thread[0], 0, &quick_sort_m,&an); pthread_join (thread[0], 0); printf("\\n----------- sorted -----------\\n"); for (j=0;j<an.count;j++) printf(" -- %d - %d --\\n",j,an.array[j]); return 0; } void help(){ printf("\\nUsage: qs [OPTION]... [SIZE]...\\nSort with quicksort algoritm a random array of SIZE, SIZE and OPTION are mandatory,SIZE must be a integer, OPTION must be [-s/-m], a default run displays this help and exit.\\n\\nMandatory arguments to long options are mandatory for short options too.\\n\\t-m run with multiprocess support\\n\\t-s 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.02\\nCopyright (C) 2014 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 3: opt = getopt(argc, argv, "s:m:"); if(opt == 's') { total=atoi(argv[2]); rtn=run_s(total); } else if (opt == 'm') { printf("2do\\n"); total=atoi(argv[2]); rtn=run_m(total); } else { help(); rtn=1; } break; default: help(); rtn=1; break; } return rtn; }
1
#include <pthread.h> pthread_mutex_t writeMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t writeThreadRelease = PTHREAD_COND_INITIALIZER; pthread_mutex_t readMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t readThreadRelease = PTHREAD_COND_INITIALIZER; pthread_cond_t rwInteraction = PTHREAD_COND_INITIALIZER; int threadcount = 16; int LOOPS = 10; int writing = 0; int reading = 0; static void cat(FILE *fp) { char buffer[4096]; rewind(fp); while (fgets(buffer, sizeof(buffer), fp) != 0){ printf("reading"); fflush(stdout); } } void *printing(void *arg){ FILE *pFile; pFile = (FILE *)arg; while(1){ pthread_mutex_lock(&writeMutex); pthread_cond_wait(&writeThreadRelease, &writeMutex); pthread_mutex_unlock(&writeMutex); if(writing < LOOPS){ pid_t pId; pId = (int)pthread_self(); printf("W- %d\\n", pId); fflush(stdout); fprintf(pFile, "%dHello", pId); writing++; if(writing >= LOOPS){ printf("W: Switch!\\n\\n"); fflush(stdout); pthread_mutex_lock(&writeMutex); pthread_cond_signal(&readThreadRelease); pthread_cond_wait(&rwInteraction, &writeMutex); writing = 0; pthread_mutex_unlock(&writeMutex); } } pthread_mutex_lock(&writeMutex); pthread_cond_signal(&writeThreadRelease); pthread_mutex_unlock(&writeMutex); printf("next print\\n\\n"); fflush(stdout); } return 0; } void *scanning(void *arg){ FILE *sFile; pid_t sId; sFile = (FILE *) arg; while(1){ while(1){ pthread_mutex_lock(&readMutex); pthread_cond_wait(&readThreadRelease, &readMutex); pthread_mutex_unlock(&readMutex); if(reading <= LOOPS){ sId = (int)pthread_self(); cat(sFile); printf("\\nR- %d\\n", sId); fflush(stdout); reading++; if(reading >= LOOPS){ break; } } pthread_mutex_lock(&readMutex); pthread_cond_signal(&readThreadRelease); pthread_mutex_unlock(&readMutex); } pthread_mutex_lock(&readMutex); pthread_cond_signal(&rwInteraction); pthread_mutex_unlock(&readMutex); reading = 0; } return 0; } int main(){ FILE *fp; fp = fopen("C:\\\\Users\\\\Barrett\\\\threadingPrCo.txt", "r+"); pthread_t threads[threadcount]; for (int i = 0; i < threadcount; i++){ if(i%2 == 0){ pthread_create(&threads[i], 0, printing, (void *)fp); } else{ pthread_create(&threads[i], 0, scanning, (void *)fp); } } pthread_mutex_lock(&writeMutex); pthread_cond_signal(&writeThreadRelease); pthread_mutex_unlock(&writeMutex); for(int m = 0; m < threadcount; m++){ pthread_join(threads[m], 0); } fclose(fp); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_lock; int waiting_students = 0; sem_t students_sem; sem_t ta_sem; void * TAWorker(); void * studentWorker(); unsigned int getRandomTime(); int main() { printf("CS149 SleepingTA from Derek Lopes\\n"); sem_init(&ta_sem, 0, 0); sem_init(&students_sem, 0, 0); pthread_mutex_init(&mutex_lock, 0); pthread_t ta_tid; pthread_t student_tids[4]; pthread_attr_t ta_attr; pthread_attr_t student_attrs[4]; pthread_attr_init(&ta_attr); pthread_create(&ta_tid, &ta_attr, TAWorker, 0); for(int i = 0; i < 4; i++) { pthread_attr_init(&student_attrs[i]); int * student_num = malloc(sizeof(int)); *student_num = i + 1; pthread_create( &student_tids[i], &student_attrs[i], studentWorker, student_num); } for(int i = 0; i < 4; i++) { pthread_join(student_tids[i], 0); } pthread_cancel(ta_tid); return 0; } void * TAWorker() { while(1) { sem_wait(&students_sem); unsigned int help_time = getRandomTime(); pthread_mutex_lock(&mutex_lock); printf("Helping a student for %d seconds, ", help_time); pthread_mutex_unlock(&mutex_lock); sem_post(&ta_sem); sleep(help_time); } } void * studentWorker(int * student_num) { int num_helped = 0; while(num_helped < 2) { unsigned int programming_time = getRandomTime(); if(programming_time != 0) { printf(" Student %d is programming for %d seconds...\\n", *student_num, programming_time); sleep(programming_time); } pthread_mutex_lock(&mutex_lock); if(waiting_students < 2) { printf(" Student %d takes a seat, ", *student_num); sem_post(&students_sem); pthread_mutex_unlock(&mutex_lock); sem_wait(&ta_sem); printf("Student %d is receiving help.\\n", *student_num); num_helped++; } else { pthread_mutex_unlock(&mutex_lock); printf(" Student %d will try again later.\\n", *student_num); } } printf("Student %d has finished.\\n", *student_num); } unsigned int getRandomTime() { clock_t time_seed = clock(); unsigned int time_seed_int = (unsigned int) time_seed; return (rand_r(&time_seed_int) % 3 + 1); }
1
#include <pthread.h> pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER; pthread_attr_t attr; int hijosVivos; void *f( void *n){ int n_local,*p; p=(int *)n; n_local=*p; printf ("Creado TH:n_local %d ((int)time:%d)\\n",n_local, (int)time(0)); sleep (4); pthread_mutex_lock (&m); hijosVivos --; printf ("FIN TH:n_local %d ((int)time:%d)\\n",n_local,(int)time(0)); pthread_mutex_unlock (&m); pthread_exit(0); } int main (){ pthread_t thid; int n=33,i,fin; pthread_mutex_init(&m, 0); pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); hijosVivos=4; for (i=1; i<=4; i++){ pthread_create (&thid, &attr, f, &i); sleep(1); } fin=0; while (!fin){ pthread_mutex_lock (&m); if (hijosVivos ==0) fin =1; pthread_mutex_unlock (&m); } printf ("Han terminado todos los threads \\n"); }
0
#include <pthread.h> extern int makethread(void *(*fn)(void *), void * arg); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip -> to_fn)(tip -> to_arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info * tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((when -> tv_sec > now.tv_sec) || (when -> tv_sec == now.tv_sec && when -> tv_nsec > now.tv_nsec )) { tip = (struct to_info *)malloc(sizeof(struct to_info)); if (tip != 0) { tip -> to_fn = func; tip -> to_arg = arg; tip -> to_wait.tv_nsec = when -> tv_sec - now.tv_sec; if (when -> tv_nsec >= now.tv_nsec) { tip -> to_wait.tv_nsec = when -> tv_nsec - now.tv_sec; } else { tip -> to_wait.tv_sec--; tip -> to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_sec; } printf("init time ok\\n"); err = makethread(timeout_helper, (void *)tip); if (err == 0) { return; } } printf("byebye!\\n"); (*func)(arg); } } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_unlock(&mutex); printf("we are trying to do something\\n"); pthread_mutex_lock(&mutex); } int main(void) { int err,arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) { err_exit(err, "pthread_mutex_init failed"); } if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) { err_exit(err, "can't set recursive type"); } if ((err = pthread_mutexattr_init(&attr)) != 0) { err_exit(err, "can not create a recursive mutex"); } pthread_mutex_lock(&mutex); printf("locked\\n"); if (1) { printf("timeout is going to be\\n"); timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; void *another(void *arg) { printf("in child thread, lock the mutex.\\n"); pthread_mutex_lock(&mutex); sleep(5); pthread_mutex_unlock(&mutex); return 0; } void prepare() { pthread_mutex_lock(&mutex); } void infork() { pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { pthread_mutex_init(&mutex, 0); pthread_t id; pthread_create(&id, 0, another, 0); sleep(1); pthread_atfork(prepare, infork, infork); int pid = fork(); if (pid < 0) { pthread_join(id, 0); pthread_mutex_destroy(&mutex); return 1; } else if (pid == 0) { printf("I am in the child, want to get the lock.\\n"); pthread_mutex_lock(&mutex); printf("I can not run to here, oop...\\n"); pthread_mutex_unlock(&mutex); exit(0); } else { wait(0); } pthread_join(id, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int count = 0; int consume( void ) { int i = 10; while( i-- ){ pthread_mutex_lock( &mutex ); pthread_cond_wait( &cond, &mutex ); printf( "Consumed %d\\n", count ); pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } void* produce( void * arg ) { int i = 10; while( i--){ pthread_mutex_lock( &mutex ); count++; printf( "Produced %d\\n", count); pthread_cond_signal( &cond ); pthread_cond_wait( &cond, &mutex ); pthread_mutex_unlock( &mutex ); } return( 0 ); } int main( void ) { pthread_t mytask_thread; pthread_create(&mytask_thread, 0, &produce, 0 ); consume(); pthread_join(mytask_thread, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int i=-1; void* someThreadFunction(){ int teller; printf("Hello from a thread!\\n"); for (teller = 0; teller < 100; teller++) { pthread_mutex_lock(&mutex); i++; pthread_mutex_unlock(&mutex); } return 0; } void* someotherThreadFunction(){ int teller; printf("Hello from another thread!\\n"); for (teller = 0; teller < 100; teller++) { pthread_mutex_lock(&mutex); i = i-1; pthread_mutex_unlock(&mutex); } return 0; } int main(){ int teller; pthread_mutex_init(&mutex,0); pthread_t someThread; pthread_create(&someThread, 0, someThreadFunction, 0); pthread_t someThread2; pthread_create(&someThread2, 0, someotherThreadFunction, 0); pthread_join(someThread, 0); pthread_join(someThread2,0); printf("Hello from main!\\n"); for (teller = 0; teller< 50; teller++) { printf("%i,\\n",i); } return 0; }
0
#include <pthread.h> pthread_mutex_t cnt_mutex; sem_t sem_write; int reader_count = 0; int content = 1; pthread_t readers[10]; void * writer_func() { printf("writer start\\n"); while (1) { sem_wait(&sem_write); content++; printf("writer: %d\\n", content); sem_post(&sem_write); } pthread_exit(0); } void * reader_func(void * n) { printf("reader start\\n"); while (1) { pthread_mutex_lock(&cnt_mutex); if (reader_count == 0) sem_wait(&sem_write); reader_count++; pthread_mutex_unlock(&cnt_mutex); printf("cur reader count:%d read_v:%d\\n", reader_count, content); pthread_mutex_lock(&cnt_mutex); reader_count--; if (reader_count == 0) sem_post(&sem_write); pthread_mutex_unlock(&cnt_mutex); } pthread_exit(0); } int main(int argc, char const* argv[]) { pthread_t writer; pthread_t reader; sem_init(&sem_write, 0, 1); pthread_create(&writer, 0, writer_func, 0); pthread_create(&reader, 0, reader_func, 0); pthread_join(writer, 0); pthread_join(reader, 0); printf("process exit\\n"); return 0; }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; struct arg{ int i; }; void cal(int i, void* p); static void* func(void *p); int main(int argc, const char *argv[]) { int err, i; pthread_t tid[4]; for (i = 0; i < 4; i++) { err = pthread_create(tid+i, 0, func, (void*)i); if (err) { fprintf(stderr, "pthread_create():%s\\n", strerror(err)); exit(1); } } for (i = 30000000; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while (num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = i; pthread_mutex_unlock(&mut_num); sleep(1); } pthread_mutex_lock(&mut_num); while (num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num=-1; pthread_mutex_unlock(&mut_num); for (i = 0; i < 4; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mut_num); exit(0); } static void* func(void *p) { int i; while (1) { pthread_mutex_lock(&mut_num); while (num == 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } if (num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_mutex_unlock(&mut_num); cal(i, p); } pthread_exit(0); } void cal(int i, void* p) { int j,mark; mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); }
0
#include <pthread.h> void *Incrementer(void *Dummy) { extern int CommonInt; extern pthread_mutex_t Mutex; sleep(rand() % 4); pthread_mutex_lock(&Mutex); if (CommonInt == 0) { sleep(rand() % 2); CommonInt += 1; printf("The common integer is now %d\\n",CommonInt); } pthread_mutex_unlock(&Mutex); return(0); } int main(int argc,char *argv[]) { extern int CommonInt; extern pthread_mutex_t Mutex; int Index; pthread_t NewThread; CommonInt = 0; srand(atoi(argv[2])); pthread_mutex_init(&Mutex,0); for (Index=0;Index<atoi(argv[1]);Index++) { if (pthread_create(&NewThread,0,Incrementer,0) != 0) { perror("Creating thread"); exit(1); } if (pthread_detach(NewThread) != 0) { perror("Detaching thread"); exit(1); } } printf("Exiting the main program, leaving the threads running\\n"); pthread_exit(0); }
1
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void pthread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int putenv_r(char *envbuf) { int i; int len; pthread_once(&init_done, pthread_init); for (i = 0; envbuf[i] != '\\0'; i++) { if (envbuf[i] == '=') break; } if (envbuf[i] == '\\0') { return 1; } pthread_mutex_lock(&env_mutex); len = i; for (i = 0; environ[i] != 0; i++) { if ((strncmp(envbuf, environ[i], len) == 0) && (environ[i][len] == '=')) { if (strcmp(&envbuf[len+1], &environ[i][len+1]) == 0) { return 0; } strcpy(environ[i], envbuf); return 0; } } if (environ[i] == 0) { environ[i] = envbuf; environ[i+1] = 0; } pthread_mutex_unlock(&env_mutex); return 0; } void *thd(void *arg) { putenv_r((char *)arg); pthread_exit((void *)0); } int main(void) { pthread_t tid1, tid2, tid3, tid4, tid5; pthread_attr_t attr; printf("sizeof0 = %ld\\n", sizeof(environ[0])); printf("sizeof1 = %ld\\n", sizeof(environ[1])); printf("sizeof2 = %ld\\n", sizeof(environ[2])); printf("sizeof3 = %ld\\n", sizeof(environ[3])); printf("sizeof4 = %ld\\n", sizeof(environ[4])); printf("strlen0 = %ld\\n", strlen(environ[0])); printf("strlen1 = %ld\\n", strlen(environ[1])); printf("strlen2 = %ld\\n", strlen(environ[2])); printf("strlen3 = %ld\\n", strlen(environ[3])); printf("strlen4 = %ld\\n", strlen(environ[4])); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&tid1, &attr, thd, (void *)"TEST1=a"); pthread_create(&tid2, &attr, thd, (void *)"TEST2=b"); pthread_create(&tid3, &attr, thd, (void *)"TEST3=c"); pthread_create(&tid4, &attr, thd, (void *)"TEST4=d"); pthread_create(&tid5, &attr, thd, (void *)"TEST5=e"); sleep(5); pthread_attr_destroy(&attr); pthread_mutex_destroy(&env_mutex); printf("TEST1 = %s\\n", getenv("TEST1")); printf("TEST2 = %s\\n", getenv("TEST2")); printf("TEST3 = %s\\n", getenv("TEST3")); printf("TEST4 = %s\\n", getenv("TEST4")); printf("TEST5 = %s\\n", getenv("TEST5")); return 0; }
0
#include <pthread.h> int buff[10]; int buff_index; pthread_mutex_t buff_mutex; sem_t buff_sem_empty; int push_front(int val) { if(buff_index < 10) { buff[buff_index++] = val; return 0; } else return -1; } int pop_front() { if(buff_index > 0) return buff[--buff_index]; else return -1; } void* producer(void* arg) { int result; while(1) { for(int i = 0 ; i < 20 ; i++) { printf("producer: sem_wait\\n"); sem_wait(&buff_sem_empty); printf("producer: po sem wait\\n"); pthread_mutex_lock(&buff_mutex); result = push_front(i); printf("producer : %d | result = %d\\n", i, result); pthread_mutex_unlock(&buff_mutex); } } } void* consumer(void* arg) { int temp; while(1) { pthread_mutex_lock(&buff_mutex); temp = pop_front(); printf("consumer : %d\\n", temp); pthread_mutex_unlock(&buff_mutex); if(temp != -1) sem_post(&buff_sem_empty); } } int main() { pthread_t th1, th2; pthread_mutex_init(&buff_mutex, 0); sem_init(&buff_sem_empty, 0, 10); pthread_create(&th1, 0, producer, 0); pthread_create(&th2, 0, consumer, 0); pthread_join(th1, 0); pthread_join(th2, 0); return 0; }
1
#include <pthread.h> struct dot_prod_data { double *a; double *b; double sum; int len; }; pthread_mutex_t mutex; struct dot_prod_data vecdata; void* worker_thread(void* data_t) { int offset=(int)(data_t); int start,end; double local_sum=0.0; int len=vecdata.len; start=(len)*offset; end=start+len; while(start<end) { local_sum+=(vecdata.a[start]*vecdata.b[start]); start++; } pthread_mutex_lock(&mutex); vecdata.sum+=local_sum; printf("----local sum for thread%f %d\\n",local_sum,offset); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(void) { pthread_attr_t attr; pthread_t tid[4]; double *a,*b; int i,rc; a=(double*) malloc((sizeof(double)*4*1000)); b=(double*) malloc((sizeof(double)*4*1000)); for(i=0;i<4*1000;++i) { a[i]=1.0; b[i]=a[i]; } vecdata.len=1000; vecdata.a=a; vecdata.b=b; vecdata.sum=0.0; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex,0); for(i=0;i<4;i++) { rc=pthread_create(tid+i,&attr,worker_thread,(void *)i); if(rc) { printf("*** error in creating thread***\\n"); exit(1); } } pthread_attr_destroy(&attr); for(i=0;i<4;++i) { pthread_join(tid[i],0); } printf("vector sum=%f\\n",vecdata.sum); free(a); free(b); pthread_mutex_destroy(&mutex); pthread_exit(0); }
0
#include <pthread.h> int gwList_insert(struct gwListNode **head, uint32_t gw){ int i = 0; pthread_mutex_lock(&gw_lock); struct gwListNode *node = *head; struct gwListNode *prev = 0; while(node){ if(gw == node->gw) break; i++; prev = node; node = node->next; } if(node == 0){ node = (struct gwListNode*)malloc(sizeof(struct gwListNode)); if(node){ node->gw = gw; node->next = 0; if(prev) prev->next = node; else *head = node; } else{ i = -1; } } pthread_mutex_unlock(&gw_lock); if(i > 0xff) i = -1; return i; } void gwList_flush(struct gwListNode **head){ pthread_mutex_lock(&gw_lock); struct gwListNode *node = *head; struct gwListNode *tmp; while(node){ tmp = node; node = node->next; free(tmp); } *head = 0; pthread_mutex_unlock(&gw_lock); }
1
#include <pthread.h> WAITTING, IDLE, ASSIGNED, BUSY }Thread_Status; pthread_t tid; pthread_mutex_t mutex; pthread_cond_t cond; Thread_Status status; task_t task; void * arg; int cnt; }Thread_pool_t; Thread_pool_t * threadPool_create_and_init(int num); int threadPool_assign_work(Thread_pool_t *pools, size_t poolnum, task_t task, void * arg); static Thread_pool_t * create_pool(int num) { int i; Thread_pool_t *pools = (Thread_pool_t *)malloc(sizeof(Thread_pool_t)*num); if (!pools) { perror("malloc"); return 0; } for (i = 0; i < num; i++) { pthread_mutex_init(&pools[i].mutex, 0); pthread_cond_init(&pools[i].cond, 0); pools[i].status = WAITTING; pools[i].task = (task_t)(0); pools[i].arg = 0; pools[i].cnt = -1; } return pools; } static void set_worker_status(Thread_pool_t *worker, Thread_Status status) { worker->status = status; } static void * worker_job(void * arg) { Thread_pool_t *worker = (Thread_pool_t *)arg; pthread_mutex_t *pmutex = &worker->mutex; pthread_cond_t *pcond = &worker->cond; while (1) { pthread_mutex_lock(pmutex); if (++worker->cnt == -1) worker->cnt = 0; worker->task = (task_t)0; worker->arg = 0; set_worker_status(worker, IDLE); ; pthread_cond_wait(pcond, pmutex); if (worker->task == (task_t)0) { pthread_mutex_unlock(pmutex); continue; } set_worker_status(worker, BUSY); pthread_mutex_unlock(pmutex); (worker->task)(worker->arg); } return 0; } static int create_threads(int num, Thread_pool_t *pools) { int i, ret; for (i = 0; i < num; i++) { ret = pthread_create(&pools[i].tid, 0, worker_job, (void *)(pools + i)); if (ret) { fprintf(stderr, "pthread_create:%s\\n", strerror(ret)); return ret; } } return ret; } static void wait_all_threads_ready(Thread_pool_t *pools, int num) { int i; for (i = 0; i < num; i++) { pthread_mutex_lock(&pools[i].mutex); if (pools[i].status == IDLE) { pthread_mutex_unlock(&pools[i].mutex); break; } else { pthread_mutex_unlock(&pools[i].mutex); sched_yield(); } } } Thread_pool_t * threadPool_create_and_init(int num) { if (num <= 0) { fprintf(stderr, "thread number invalied!\\n"); return 0; } Thread_pool_t *pools; int ret; pools = create_pool(num); if (pools == 0) return 0; ret = create_threads(num, pools); if (ret) return 0; wait_all_threads_ready(pools, num); return pools; } int threadPool_assign_work(Thread_pool_t *pools, size_t poolnum, task_t task, void * arg) { if (!task || !pools || poolnum <= 0) { fprintf(stderr, "argument ivalied!\\n"); return -1; } int i, index = -1, cnt = -1; for (i = 0; i < poolnum; i++) { pthread_mutex_lock(&pools[i].mutex); if (pools[i].status == IDLE) { if (index == -1) { index = i; cnt = pools[i].cnt; }else { if (cnt > pools[i].cnt) { index = i; cnt = pools[i].cnt; } } } pthread_mutex_unlock(&pools[i].mutex); } if (index == -1) { fprintf(stderr, "ALL threads was busy!\\n"); return -1; }else { pthread_mutex_lock(&pools[index].mutex); pools[index].task = task; pools[index].arg = arg; set_worker_status(pools + index, ASSIGNED); pthread_cond_signal(&pools[index].cond); pthread_mutex_unlock(&pools[index].mutex); } return 0; } void task(void *arg) { printf("task %d begin!\\n", (int)arg); srand(pthread_self()); sleep(rand()%5 + 3); printf("task %d over!\\n", (int)arg); } int main(void) { Thread_pool_t *pools; int i, ret, k; printf("输入要创建的进程数量: "); scanf("%d", &k); pools = threadPool_create_and_init(k); if (!pools) return -1; while (1) { printf("Input task: "); fflush(stdout); scanf("%d", &i); ret = threadPool_assign_work(pools, k, task, (void *)i); if (-1 == ret) continue; } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long double buffer[3] = {1, 1, 1}; void * fibonacci_entry(void *lim) { long double *prev1 = &buffer[1]; long double *prev2 = &buffer[2]; for (int i = 1; i < *(int*)lim; i++) { pthread_mutex_lock(&mutex); if (i == 1) { buffer[0] = 1; } else { long double tmp = *prev2; *prev2 = *prev2 + *prev1; *prev1 = tmp; buffer[0] = *prev2; } pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char **argv) { pthread_t worker; int lim; int ncomplete = 1; if (argc < 2) { fprintf(stderr, "usage: fibonacci lim\\n"); return -1; } lim = atoi(argv[1]); if (lim > 100) { fprintf(stderr, "lim <= 100\\n"); return -1; } pthread_create(&worker, 0, fibonacci_entry, &lim); while (ncomplete != lim + 1) { pthread_mutex_lock(&mutex); printf("[%d] - %.0Lf\\n", ncomplete, buffer[0]); pthread_mutex_unlock(&mutex); ncomplete++; } return 0; }
1
#include <pthread.h> void mediafirefs_destroy(void *user_ptr) { printf("FUNCTION: destroy\\n"); FILE *fd; struct mediafirefs_context_private *ctx; ctx = (struct mediafirefs_context_private *)user_ptr; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "storing hashtable\\n"); fd = fopen(ctx->dircache, "w+"); if (fd == 0) { fprintf(stderr, "cannot open %s for writing\\n", ctx->dircache); pthread_mutex_unlock(&(ctx->mutex)); return; } folder_tree_store(ctx->tree, fd); fclose(fd); folder_tree_destroy(ctx->tree); mfconn_destroy(ctx->conn); pthread_mutex_unlock(&(ctx->mutex)); }
0
#include <pthread.h> pthread_mutex_t mAvailable; pthread_mutex_t mAllocation; pthread_mutex_t mNeed; int available[3]; int maximum[5][3]; int allocation[5][3]; int need[5][3]; void show_matrix(int array[5][3], char *array_name); int request_resources(int customer, int resources[]); int release_resources(int customer, int resources[]); int check_if_safe(); void init_maximum() { srand(time(0)); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { maximum[i][j] = rand() % available[j]; allocation[i][j] = 0; } } } int release(int customer, int resources[], int safe) { for (int i = 0; i < 3; i++) { pthread_mutex_lock(&mAllocation); allocation[customer][i] -= resources[i]; pthread_mutex_unlock(&mAllocation); pthread_mutex_lock(&mAvailable); available[i] += resources[i]; pthread_mutex_unlock(&mAvailable); pthread_mutex_lock(&mNeed); need[customer][i] += maximum[customer][i] + allocation[customer][i]; pthread_mutex_unlock(&mNeed); } if (safe < 0) { return 1; } return 0; } int request(int customer, int resources[]) { for (int i = 0; i < 3; i++) { pthread_mutex_lock(&mAllocation); allocation[customer][i] += resources[i]; pthread_mutex_unlock(&mAllocation); pthread_mutex_lock(&mAvailable); available[i] -= resources[i]; pthread_mutex_unlock(&mAvailable); pthread_mutex_lock(&mNeed); need[customer][i] -= resources[i]; pthread_mutex_unlock(&mNeed); } int safe = check_if_safe(); if (safe < 0) { return release(customer, resources, safe); } return 0; } int request_resources(int customer, int resources[]) { printf("\\nRecieved request from customer: %d\\n", customer); for (int i = 0; i < 3; i++) printf("%d, ", resources[i]); printf("\\n"); for (int i = 0; i < 3; i++) { if (resources[i] > need[customer][i]) return 1; } printf("\\nResources available:\\n"); for (int i = 0; i < 3; i++) printf("%d, ", available[i]); printf("\\n"); show_matrix(allocation, "Allocation"); show_matrix(need, "Need"); show_matrix(maximum, "Maximum"); return request(customer, resources); } int release_resources(int customer, int resources[]) { return release(customer, resources, 0); } int check_if_safe() { int work[3], finish[5], success = 0; for (int i = 0; i < 3; i++) work[i] = available[i]; for (int i = 0; i < 5; i++) finish[i] = 0; for (int i = 0; i < 5; i++) { if (finish[i] == 0) { for (int j = 0; i < 3; i++) { if (need[i][j] > work[j]) return -1; } for (int j = 0; j < 3; j++) work[j] += allocation[i][j]; success = 1; } } return success; } void *create_thread(void *customer) { int request[3], flag = 0; int customer_number = (int)customer; for (int i = 0; i < 3; i++) request[i] = rand() % available[i]; if (request_resources(customer_number, request) < 0) { printf("Customer %d: Request Denied.\\n", customer_number); } else { flag = 1; printf("Customer %d: Request Accepted.\\n", customer_number); } if (flag == 1) { sleep(rand() % 10); release_resources(customer_number, request); printf("\\nReleased resources from customer: %d\\n", customer_number); } } void show_matrix(int matrix[5][3], char *name) { printf("\\nMatrix: %s\\n", name); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) printf("%d, ", matrix[i][j]); printf("\\n"); } printf("\\n"); } int main(int argc, const char * argv[]) { int customer_count = 0; int count = 40; pthread_t tid; printf("Program started.\\n\\n"); if ((3 + 1) == argc) { printf("\\nResources available:\\n"); for (int i = 0; i < 3; i++) { available[i] = atoi(argv[i + 1]); printf("%d, ", available[i]); } printf("\\n"); } init_maximum(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) need[i][j] = maximum[i][j] - allocation[i][j]; } show_matrix(maximum, "Maximum"); show_matrix(need, "Need"); for (int i = 0; i < count; i++) { for (int j = 0; j < 5; j++) { printf("\\nCreating customer with id: %d", j); pthread_create(&tid, 0, create_thread, (void *)j); } } printf("\\nExiting Program\\n"); return 0; }
1
#include <pthread.h> void *ta (void *arg); void *tb (void *arg); void *tc (void *arg); void *td (void *arg); pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; void *ta (void *arg) { pthread_t c; (void) arg; printf ("ta: running\\n"); pthread_mutex_lock (&m1); pthread_mutex_unlock (&m1); pthread_create (&c, 0, tc, 0); return 0; } void *tb (void *arg) { pthread_t d; (void) arg; printf ("tb: running\\n"); pthread_create (&d, 0, td, 0); pthread_mutex_lock (&m1); pthread_mutex_unlock (&m1); pthread_mutex_lock (&m2); pthread_mutex_unlock (&m2); return 0; } void *tc (void *arg) { (void) arg; printf ("tc: running\\n"); return 0; } void *td (void *arg) { (void) arg; printf ("td: running\\n"); pthread_mutex_lock (&m2); pthread_mutex_unlock (&m2); return 0; } int main() { pthread_t a, b; pthread_create (&a, 0, ta, 0); pthread_create (&b, 0, tb, 0); pthread_exit (0); }
0
#include <pthread.h> double *A; int num_threads = 2; int N = 33554432; int ocurrencia = 0; double buscar = 1; double maximun_value; double minimun_value; pthread_mutex_t A_lock; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *find_max_min(void *aux){ int id = *(int*)aux; int i; double my_min = A[0], my_max = A[0]; int limite = N/num_threads; int base = id*limite; int fin = (id+1)*limite; for(i = base;i < fin; i++ ){ if(A[i] > my_max){ my_max = A[i]; }else if(A[i] < my_min){ my_min = A[i]; } } pthread_mutex_lock(&A_lock); if (my_min < minimun_value) minimun_value = my_min; if (my_max > maximun_value) maximun_value = my_max; pthread_mutex_unlock(&A_lock); } int main(int argc, char *argv[]){ if(argc != 2){ return 1; } num_threads = atoi(argv[1]); double timetick; int i; int ids[num_threads]; for(i = 0; i < num_threads; i++){ ids[i] = i; } A=(double*)malloc(sizeof(double)*N); for(i = 0; i < N; i++){ A[i] = 5; } A[352] = 1.0; A[23554432] = 48612.0; maximun_value = A[0]; minimun_value = A[0]; pthread_t p_threads[num_threads]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&A_lock, 0); for(i=0; i< num_threads; i++){ pthread_create(&p_threads[i], &attr, find_max_min, (void*) &ids[i]); } timetick = dwalltime(); for(i=0; i< num_threads; i++){ pthread_join(p_threads[i], 0); } printf("Tiempo en segundos %f\\n", dwalltime() - timetick); free(A); return 0; }
1
#include <pthread.h> static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; static void * thr_func(void *p) { FILE *fp; char buf[1024]; fp = fopen("/tmp/out","r+"); if(fp == 0) { perror("fopen"); exit(1); } pthread_mutex_lock(&mut); fgets(buf,1024,fp); fseek(fp,0,0); fprintf(fp,"%d\\n",atoi(buf)+1); fclose(fp); pthread_mutex_unlock(&mut); pthread_exit(0); } int main() { int i,err; pthread_t tid[20]; for(i = 0 ; i < 20 ; i++) { err = pthread_create(tid+i,0,thr_func,0); if(err) { fprintf(stderr,"pthread_create()%s\\n",strerror(err)); exit(1); } } for(i = 0 ; i < 20 ; i++) { pthread_join(tid[i],0); } pthread_mutex_destroy(&mut); exit(0); }
0
#include <pthread.h> int i, int_rand, x, y, z; int tamanhoFila, nrExames; float float_rand; int matrizDados[4][2]; pthread_mutex_t mutex; sem_t sem_sensores[5]; struct Node{ int conjuntoDados[2][2]; struct Node *proximo; }; Node *fila; int tamanhoFila, nodoAtual; void inicializaFila(Node *fila) { fila->proximo = 0; tamanhoFila=0; nodoAtual=0; } int filaVazia(){ if(fila->proximo == 0){ return 1; } else{ return 0; } } void liberaFila(){ if(!filaVazia()){ Node *proximoNodo, *atual; atual = fila->proximo; while(atual != 0){ proximoNodo = atual->proximo; free(atual); atual = proximoNodo; } } tamanhoFila=0; } void insereNodoFila(Node *novoNodo){ if(filaVazia()){ fila->proximo=novoNodo; }else{ Node *tmp = fila->proximo; while(tmp->proximo != 0){ tmp = tmp->proximo; } tmp->proximo = novoNodo; } tamanhoFila++; } void liberaMatriz(){ for(y = 0; y < 4; y++){ matrizDados[y][0] = -1; matrizDados[y][1] = -1; } } void monitor(){ Node *nodoA=(Node *) malloc(sizeof(Node)); Node *nodoB=(Node *) malloc(sizeof(Node)); nodoA->proximo=0; nodoB->proximo=0; for(y=0; y<2; y++){ for(z=0; z<2; z++){ nodoA->conjuntoDados[y][z] = matrizDados[y][z]; nodoB->conjuntoDados[y][z] = matrizDados[y+2][z]; } } insereNodoFila(nodoA); insereNodoFila(nodoB); liberaMatriz(); } int idPresente(int id){ for(z=0; z<4; z++){ if(matrizDados[z][0]==id){ return 0; } } return 1; } void printaMatriz(){ int cont; printf("\\n\\n--------- Coleta -----------"); for(cont=0; cont<4; cont++){ printf("\\nO sensor de id %d coletou o dado %d", matrizDados[cont][0], matrizDados[cont][1]); } } void coletar(int id){ int dado=(random()%150); for(x=0; x<4; x++){ pthread_mutex_lock(&mutex); if(matrizDados[x][0]==-1){ if(idPresente(id)){ matrizDados[x][0]=id; matrizDados[x][1]=dado; if(x==2 -1){ printaMatriz(); monitor(); for(z=0; z<5; z++){ if(z!=id){ sem_post(&sem_sensores[z]); } } pthread_mutex_unlock(&mutex); sleep(3); }else{ pthread_mutex_unlock(&mutex); sem_wait(&sem_sensores[id]); } }else{ pthread_mutex_unlock(&mutex); sem_wait(&sem_sensores[id]); } }else{ pthread_mutex_unlock(&mutex); } } } void *acao_sensor(void *j){ int i = *(int*) j; while(tamanhoFila<20){ sleep(1); coletar(i); } } void visualizar(){ int dadosSensores[5][20]; Node *tmp; tmp = fila->proximo; int countDados[5]={0, 0, 0, 0, 0}; while( tmp != 0){ for(y=0; y<2; y++){ int idAux = tmp->conjuntoDados[y][0]; dadosSensores[idAux][countDados[idAux]]=tmp->conjuntoDados[y][1]; countDados[idAux]++; } tmp = tmp->proximo; } double media; double acmDados; for(y=0; y<5; y++){ acmDados=0; for(z=0; z<countDados[y]; z++){ acmDados+=dadosSensores[y][z]; } media = acmDados/countDados[y]; printf("\\n\\n------------------------ Sensor ID %d ------------------------", y); switch (y) { case 0: printf("\\nA média coletada pelo sensor de ritmo cardíaco é: %.2f", media); break; case 1: printf("\\nA média coletada pelo sensor de suprimento sanguíneo é: %.2f", media); break; case 2: printf("\\nA média coletada pelo sensor de suprimento de oxigênio é: %.2f", media); break; case 3: printf("\\nA média coletada pelo sensor de despolarização atrial é: %.2f", media); break; case 4: printf("\\nA média coletada pelo sensor de repolarização ventricular é: %.2f", media); break; } printf("\\nA quantidade de vezes que foi escolhido: %d", countDados[y]); } } int main(){ int opcao, opcao2; fila = (Node *) malloc(sizeof(Node)); inicializaFila(fila); nrExames = 0; liberaMatriz(); pthread_t thread[5]; void *thread_result; pthread_mutex_init(&mutex, 0); for(i=0; i<5; i++) sem_init(&sem_sensores[i], 0, 0); do{ printf("Escolha uma das opções abaixo:\\n1 - Iniciar o exame;\\n0 - Encerrar o sistema;\\n"); scanf("%d", &opcao); switch(opcao){ case 1: printf("Início do Exame\\n"); liberaFila(); int array[5]; for(i=0; i<5; i++){ array[i]=i; pthread_create(&thread[i], 0, acao_sensor, &array[i]); } for(i=0; i<5; i++) pthread_join(thread[i], &thread_result); do{ printf("\\n\\nExame realizado!\\nEscolha uma das opções abaixo:\\n1 - Exibir o resultado dos dados coletados;\\n0 - Encerrar;\\n"); scanf("%d", &opcao); switch(opcao){ case 1: visualizar(); break; case 0: printf("\\nFim do exame\\n"); break; default: printf("Erro! Digite novamente"); break; } }while(opcao!=0); case 0: printf("\\nFim da execução.\\n"); break; default: printf("Erro! Digite novamente"); } } while(opcao!=0); return 0; }
1
#include <pthread.h> pthread_mutex_t globalNumberLock; int globalNumber=0; void* thread_1(){ for(int i=0; i<1000000; i++){ pthread_mutex_lock(&globalNumberLock); globalNumber++; pthread_mutex_unlock(&globalNumberLock); } return 0; } void* thread_2(){ for (int j=0; j<1000001; j++){ pthread_mutex_lock(&globalNumberLock); globalNumber--; pthread_mutex_unlock(&globalNumberLock); } return 0; } int main(){ pthread_mutex_init(&globalNumberLock,0); pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, thread_1, 0); pthread_create(&thread2, 0, thread_2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&globalNumberLock); printf("This is the resulting globalNUmber %d \\n", globalNumber); return 0; }
0
#include <pthread.h> int nitems; int buf[1000000]; struct { pthread_mutex_t mutex; int nput; int nval; }put = {PTHREAD_MUTEX_INITIALIZER}; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; }nready = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER}; void *produce(void*), *consume(void*); int main(int argc, char **argv) { int i, nthreads, count[100]; pthread_t tid_produce[100], tid_consume; if (argc != 3) { fprintf(stderr, "usage:exename <items> <threads>\\n"); exit(-1); } nitems = ((atoi(argv[1])) < (1000000) ? (atoi(argv[1])) : (1000000)); nthreads = ((atoi(argv[2])) < (100) ? (atoi(argv[2])) : (100)); pthread_setconcurrency(nthreads); for (i = 0; i < nthreads; i++) { count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } pthread_create(&tid_consume, 0, consume, 0); for (i = 0; i < nthreads; i++) { pthread_join(tid_produce[i], 0); printf("count[%d] = %d\\n", i, count[i]); } pthread_join(tid_consume, 0); exit(0); } void *produce(void *arg) { for (;;) { pthread_mutex_lock(&put.mutex); if (put.nput >= nitems) { pthread_mutex_unlock(&put.mutex); return; } buf[put.nput] = put.nval; put.nput++; put.nval++; pthread_mutex_unlock(&put.mutex); int dosignal; pthread_mutex_lock(&nready.mutex); dosignal = (nready.nready == 0); nready.nready++; pthread_mutex_unlock(&nready.mutex); if (dosignal) pthread_cond_signal(&nready.cond); *((int*)arg) += 1; } } void *consume(void *arg) { int i; for (i = 0; i < nitems; i++) { pthread_mutex_lock(&nready.mutex); while (nready.nready == 0) pthread_cond_wait(&nready.cond, &nready.mutex); nready.nready--; pthread_mutex_unlock(&nready.mutex); if (buf[i] != i) { printf("buff[%d] = %d\\n", i, buf[i]); } } return 0; }
1
#include <pthread.h> static int global = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t v = PTHREAD_COND_INITIALIZER; void perror_exit (const char *info) { perror (info); exit (1); } void *count_times (void *args) { int i = 1; while (1) { sleep (1); fprintf (stderr, "second: %d\\n", i++); } return (void *) 0; } void *tfn (void *args) { pthread_mutex_lock (&m); while (global !=100) pthread_cond_wait (&v, &m); fprintf (stderr, "t%d: global = %d\\n", (int) args, global); pthread_mutex_unlock (&m); return (void *) 0; } int main (int argc, char **argv) { if (argc != 2) { fprintf (stderr, "Usage: %s threads-number\\n", argv[0]); return -1; } pthread_mutex_init (&m, 0); pthread_cond_init (&v, 0); pthread_t tid; pthread_create (&tid, 0, count_times, 0); int i; int thread_nums = atoi (argv[1]); for (i = 0; i < thread_nums; i++) if (pthread_create (&tid, 0, tfn, (void *) i) != 0) perror_exit ("pthread_create falied"); sleep (1); pthread_mutex_lock (&m); global = 100; pthread_cond_broadcast (&v); sleep (3); pthread_mutex_unlock (&m); sleep (2); pthread_exit (0); }
0
#include <pthread.h> static pthread_mutex_t lock; static pthread_barrier_t barrier; int* counterArray; int nthreads; int ncounters; void* chain(void* arglist) { int i, j; for (i = 0; i < nthreads; i++) { pthread_mutex_lock(&lock); for (j = 0; j < ncounters; j++) counterArray[j*16]++; pthread_mutex_unlock(&lock); pthread_barrier_wait(&barrier); } return 0; } int main(int argc, const char** const argv) { if (argc != 3) { printf("Usage: ./microbench2 <nthreads> <ncounters>\\n"); exit(1); } nthreads = atoi(argv[1]); ncounters = atoi(argv[2]); if (nthreads < 2 || ncounters < 1) { printf("This test requires at least 2 CPUs, 1 counter variable\\n"); exit(1); } int i; pthread_t pth[nthreads]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&lock, 0); printf("Init done\\n"); pthread_barrier_init(&barrier, 0, nthreads); counterArray = (int*) calloc(ncounters*16, sizeof(int)); for (i = 0; i < nthreads; i++) { pthread_create(&pth[i], &attr, chain, 0); } for (i = 0; i < nthreads; i++) { pthread_join(pth[i], 0); } printf("Val: %d\\n", counterArray[0]); printf("PASSED :-)\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t lock_mutex; char *buf="hello zmw"; sem_t empty,full; char buf1[50]; int fileopen; void *readfile(void *arg) { sem_wait(&empty); pthread_mutex_lock(&lock_mutex); char pro=*(char*)arg; read(fileopen,buf1,100); printf("%c read from pipe is: %s\\n",pro,buf1); sem_post(&full); pthread_mutex_unlock(&lock_mutex); return 0; } void *writefile(void *arg) { sem_wait(&full); pthread_mutex_lock(&lock_mutex); char pro=*(char*)arg; write(fileopen,buf,100); printf("childthread%c write to pipe %s\\n",pro,buf); sem_post(&empty); pthread_mutex_unlock(&lock_mutex); return 0; } int main() { fileopen=open("/home/zmw/文档/第五周/test.txt",O_RDWR|O_CREAT); pthread_t childA; pthread_t childB; int child_pthreadA; int child_pthreadB; sem_init(&empty,0,2); sem_init(&full,0,0); child_pthreadA=pthread_create(&childA,0,writefile,"A"); if(child_pthreadA!=0) { printf("A线程创建失败\\n"); } if(child_pthreadB!=0) { printf("B线程创建失败\\n"); } printf("线程创建成功!\\n"); child_pthreadB=pthread_create(&childB,0,readfile,"B"); pthread_join(childA,0); pthread_join(childB,0); return 0; }
0
#include <pthread.h> int done; FILE *file; pthread_mutex_t lock1; pthread_mutex_t lock2; pthread_mutex_t filelock; char filename[]="MyMessage.log"; struct thread_person { pthread_t thread_id; int thread_num; pthread_attr_t attr; int start_flag; int quit_flag; int join_flag; int create_flag; int linecount; int initialze; char message[256]; }; static void *thread_start(void *arg) { struct thread_person *person=(struct thread_person*)arg; if (pthread_mutex_lock(&lock1)!=0) fprintf(stderr,"Failed to lock the mutex in thread %d \\n",0 ); if(person->start_flag==0){ done++; person->start_flag=1; } printf("[pid=%d,tid=%lu,index=%d,name=Person%d]\\n",getpid(),(unsigned long)pthread_self(),person->thread_num,person->thread_num); printf("Enter Message : "); fgets(&person->message[0],256,stdin); pthread_mutex_unlock(&lock1); char qmsg[4]="quit"; if(person->message[0]=='q' && person->message[1]=='u' && person->message[2] == 'i' && person->message[3]=='t'){ pthread_mutex_lock(&lock2); done--; person->quit_flag=1; pthread_mutex_unlock(&lock2); pthread_exit(0); }else{ person->linecount++; person->create_flag=0; pthread_mutex_lock(&filelock); if(file==0){ file=fopen(filename,"w"); } fprintf(file,"[pid=%d,tid=%lu,index=%d,name=Person%d]\\n",getpid(),(unsigned long)pthread_self(),person->thread_num,person->thread_num); fprintf(file,"Enter Message : %s \\n",person->message); pthread_mutex_unlock(&filelock); } pthread_exit(0); } int main(int argc, char **argv) { struct thread_person *persons; if((persons = calloc(3, sizeof(struct thread_person)))==0) perror("failed to allocate memory for struct person"); if (pthread_mutex_init(&lock1, 0) != 0 && pthread_mutex_init(&lock2, 0) != 0 && pthread_mutex_init(&filelock,0) !=0 ) { printf("\\n mutex init failed\\n"); return 1; } do{ for (int i=0;i<3;i++){ if(persons[i].create_flag==0){ if(persons[i].quit_flag==0){ persons[i].thread_num=i; pthread_attr_init(&persons[i].attr); persons[i].create_flag=1; pthread_create(&persons[i].thread_id,&persons[i].attr,&thread_start,&persons[i]); } } } for (int i;i<3;i++){ if(persons[i].create_flag==1){ pthread_join(persons[i].thread_id,0);} } }while(done); if(file!=0){ fclose(file); } printf("\\n"); for (int i=0;i<3;i++){ printf("Person person%d processed %d lines \\n",i,persons[i].linecount); } pthread_exit(0); }
1
#include <pthread.h> int QUIT = 0; pthread_mutex_t INUSE; unsigned char byte; FILE* PARLELPORT; void *all_blink(void* arg) { QUIT = 0; pthread_mutex_lock(&INUSE); while (1) { byte = 0xFF; fwrite(&byte, 1, 1, PARLELPORT); sleep(0.5); byte = 0; fwrite(&byte, 1, 1, PARLELPORT); sleep(0.5); if (QUIT == 1) { pthread_mutex_unlock(&INUSE); pthread_exit(0); } } } void *all_on(void* arg) { QUIT = 0; pthread_mutex_lock(&INUSE); byte = 0xFF; fwrite(&byte, 1, 1, PARLELPORT); while (1) { if (QUIT == 1) break; } byte = 0; fwrite(&byte, 1, 1, PARLELPORT); pthread_mutex_unlock(&INUSE); pthread_exit(0); } void *one_one(void* arg) { QUIT = 0; pthread_mutex_lock(&INUSE); byte = 1; while (1) { fwrite(&byte, 1, 1, PARLELPORT); byte <<= 1; if (QUIT == 1) break; if (byte == 0) byte = 1; sleep(0.5); } byte = 0; fwrite(&byte, 1, 1, PARLELPORT); pthread_mutex_unlock(&INUSE); pthread_exit(0); } void *random_t(void* arg) { QUIT = 0; pthread_mutex_lock(&INUSE); time_t seconds; seconds = time(0); srand((unsigned)seconds); while(1) { byte = (char)(rand() % 256); fwrite(&byte, 1, 1, PARLELPORT); sleep(0.5); if (QUIT == 1) break; } byte = 0; fwrite(&byte, 1, 1, PARLELPORT); pthread_mutex_unlock(&INUSE); pthread_exit(0); } int main() { char dummy; int opt; PARLELPORT = fopen("/dev/parlelport", "w"); setvbuf(PARLELPORT, &dummy, _IONBF, 1); pthread_t start, all_lights_on, all_lights_blinking, one_by_one, random; pthread_mutex_init(&INUSE, 0); pthread_create(&start, 0, all_blink, 0); while (1) { printf("Welcome to our LED show! Please select an option:\\n"); printf("1. All lights on\\n2. All lights blinking\\n3. One by one\\n4. Random\\n5. Exit\\n"); scanf("%d", &opt); if ((opt > 5) || (opt < 1)) { printf("Sorry! That is outside the range. Please try again:\\n"); sleep(0.5); break; } QUIT = 1; switch(opt) { case 1: pthread_create(&start, 0, all_blink, 0); break; case 2: pthread_create(&all_lights_on, 0, all_on, 0); break; case 3: pthread_create(&one_by_one, 0, one_one, 0); break; case 4: pthread_create(&random, 0, random_t, 0); break; case 5: fclose(PARLELPORT); exit(0); } } return 0; }
0
#include <pthread.h> void *producer (void *args); void *consumer (void *args); int buf[10]; long head, tail; int full, empty; pthread_mutex_t *mut; pthread_cond_t *notFull, *notEmpty; } queue; queue *queueInit (void); void queueDelete (queue *q); void queueAdd (queue *q, int in); void queueDel (queue *q, int *out); int main () { queue *fifo; pthread_t pro, con; fifo = queueInit (); if (fifo == 0) { fprintf (stderr, "main: Queue Init failed.\\n"); exit (1); } pthread_create (&pro, 0, producer, fifo); pthread_create (&con, 0, consumer, fifo); pthread_join (pro, 0); pthread_join (con, 0); queueDelete (fifo); return 0; } void *producer (void *q) { queue *fifo; int i; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); usleep (100000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); usleep (200000); } return (0); } void *consumer (void *q) { queue *fifo; int i, d; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep(200000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep (50000); } return (0); } queue *queueInit (void) { queue *q; q = (queue *)malloc (sizeof (queue)); if (q == 0) return (0); q->empty = 1; q->full = 0; q->head = 0; q->tail = 0; q->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (q->mut, 0); q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notFull, 0); q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notEmpty, 0); return (q); } void queueDelete (queue *q) { pthread_mutex_destroy (q->mut); free (q->mut); pthread_cond_destroy (q->notFull); free (q->notFull); pthread_cond_destroy (q->notEmpty); free (q->notEmpty); free (q); } void queueAdd (queue *q, int in) { q->buf[q->tail] = in; q->tail++; if (q->tail == 10) q->tail = 0; if (q->tail == q->head) q->full = 1; q->empty = 0; return; } void queueDel (queue *q, int *out) { *out = q->buf[q->head]; q->head++; if (q->head == 10) q->head = 0; if (q->head == q->tail) q->empty = 1; q->full = 0; return; }
1
#include <pthread.h> pthread_cond_t full = PTHREAD_COND_INITIALIZER, empty = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int buffer[4]; int begin = 0, end = 0, counter = 0, max = 4; void *producer( void *arg ){ printf("pthread producer id : %d run \\n", *(int *) arg ); srand(1); while( 1 ) { pthread_mutex_lock( &mutex ); while( counter == max ) pthread_cond_wait( &full, &mutex ); buffer[ end ] = rand()%10; counter++; printf("pthread producer id :%d produce at %d and counter is %d\\n", *(int *) arg, buffer[ end ], counter ); end = ++end % max; pthread_mutex_unlock( &mutex ); pthread_cond_signal( &empty ); } return 0; } void *consumer( void *arg ) { printf("pthread consumer id : %d run \\n", *(int *)arg ); while( 1 ) { pthread_mutex_lock( &mutex ); while( counter == 0 ) pthread_cond_wait( &empty, &mutex ); counter--; printf("pthread consumer id :%d consumer at %d and counter is %d\\n", *(int *) arg, buffer[ begin ], counter ); begin = ++begin % max; pthread_mutex_unlock( &mutex ); pthread_cond_signal( &full ); } return 0; } int main(int argc, char const *argv[]) { pthread_t pthread_consumer[3]; pthread_t pthread_producer[2]; int index = 0, *p = 0 ; for( index = 0; index < 3; index++ ) { p = (int *)malloc( sizeof(int) ); *p = index; if( pthread_create( &pthread_consumer[ index ], 0, producer, p ) != 0) { printf("create consumer error\\n"); return -1; } } for( index = 0; index < 2; index++ ) { p = (int *)malloc( sizeof(int) ); *p = index; if( pthread_create( &pthread_producer[ index ], 0, consumer, p ) != 0) { printf("create consumer error\\n"); return -1; } } for( index = 0; index < 3; index++ ) pthread_join( pthread_consumer[ index ], 0 ); for( index = 0; index < 2; index++ ) pthread_join( pthread_producer[ index ], 0 ); return 0; }
0
#include <pthread.h> int nitems; int buff[1000000]; struct { pthread_mutex_t mutex; int nput; int nval; } put = { PTHREAD_MUTEX_INITIALIZER }; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; } nready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; int nsignals; void *produce(void *), *consume(void *); int main(int argc, char **argv) { int i, nthreads, count[100]; pthread_t tid_produce[100], tid_consume; if (argc != 3) { return 1; } nitems = (((atoi(argv[1])) < (1000000))?(atoi(argv[1])):(1000000)); nthreads = (((atoi(argv[2])) < (100))?(atoi(argv[2])):(100)); for (i = 0; i < nthreads; i++) { count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } pthread_create(&tid_consume, 0, consume, 0); for (i = 0; i < nthreads; i++) { pthread_join(tid_produce[i], 0); printf("count[%d] = %d\\n", i, count[i]); } pthread_join(tid_consume, 0); printf("nsignals = %d\\n", nsignals); exit(0); } void * produce(void *arg) { for ( ; ; ) { pthread_mutex_lock(&put.mutex); if (put.nput >= nitems) { pthread_mutex_unlock(&put.mutex); return(0); } buff[put.nput] = put.nval; put.nput++; put.nval++; pthread_mutex_unlock(&put.mutex); pthread_mutex_lock(&nready.mutex); if (nready.nready == 0) { pthread_cond_signal(&nready.cond); nsignals++; } nready.nready++; pthread_mutex_unlock(&nready.mutex); *((int *) arg) += 1; } } void * consume(void *arg) { int i; for (i = 0; i < nitems; i++) { pthread_mutex_lock(&nready.mutex); while (nready.nready == 0) pthread_cond_wait(&nready.cond, &nready.mutex); nready.nready--; pthread_mutex_unlock(&nready.mutex); if (buff[i] != i) printf("buff[%d] = %d\\n", i, buff[i]); } return(0); }
1
#include <pthread.h> const char* __op_to_str(int op) { switch(op) { case 1: return "Begin of access"; case 2: return "Begin of write"; case 3: return "End of write"; case 4: return "Begin of read"; case 5: return "End of read"; case 6: return "End of read/write"; } } pthread_mutex_t write_mutex; void callback(int op, int arg1, int arg2) { pthread_mutex_lock(&write_mutex); printf("%s %d %d\\n", __op_to_str(op), arg1, arg2); fflush(stdout); pthread_mutex_unlock(&write_mutex); } const int PAGE_SIZE = 64, MEM_SIZE = 30, ADDR_SPACE_SIZE = 80, MAX_CONCURRENT_OPERATIONS = 2, MAGIC_PRIME = 37, THREAD_COUNT = 17; void* check(void* data) { int thread_id = rand() % THREAD_COUNT; unsigned i; for (i = 0; i < PAGE_SIZE * ADDR_SPACE_SIZE / THREAD_COUNT - 1; i++) { int8_t value; int addr = i * THREAD_COUNT + thread_id; int result = page_sim_set(addr, addr % MAGIC_PRIME); assert(result != -1); assert(-1 != page_sim_get(addr, &value)); assert(value == addr % MAGIC_PRIME); } for (i = 0; i < PAGE_SIZE * ADDR_SPACE_SIZE / THREAD_COUNT - 1; i++) { int8_t value; int addr = i * THREAD_COUNT + thread_id; assert(-1 != page_sim_get(addr, &value)); assert(value == addr % MAGIC_PRIME); } pthread_exit(0); } int main() { page_sim_init( PAGE_SIZE, MEM_SIZE, ADDR_SPACE_SIZE, MAX_CONCURRENT_OPERATIONS, callback); pthread_mutex_init(&write_mutex, 0); pthread_t threads[THREAD_COUNT]; int i = 0; for(; i < THREAD_COUNT; i++) if (pthread_create(&threads[i], 0, check, 0)) { printf("Pthread error\\n"); return 1; } for(i = 0; i < THREAD_COUNT; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&write_mutex); assert(page_sim_end() == 0); }
0
#include <pthread.h> int count = 0; double finalresult=0.0; pthread_mutex_t count_mutex; pthread_cond_t count_condvar; void *sub1(void *t) { int i; long tid = (long)t; double myresult=0.0; sleep(1); pthread_mutex_lock(&count_mutex); printf("sub1: thread=%ld going into wait. count=%d\\n",tid,count); pthread_cond_wait(&count_condvar, &count_mutex); printf("sub1: thread=%ld Condition variable signal received.",tid); printf(" count=%d\\n",count); count++; finalresult += myresult; printf("sub1: thread=%ld count now equals=%d myresult=%e. Done.\\n", tid,count,myresult); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } void *sub2(void *t) { int j,i; long tid = (long)t; double myresult=0.0; for (i=0; i<10; i++) { for (j=0; j<100000; j++) myresult += sin(j) * tan(i); pthread_mutex_lock(&count_mutex); finalresult += myresult; count++; if (count == 12) { printf("sub2: thread=%ld Threshold reached. count=%d. ",tid,count); pthread_cond_signal(&count_condvar); printf("Just sent signal.\\n"); } else { printf("sub2: thread=%ld did work. count=%d\\n",tid,count); } pthread_mutex_unlock(&count_mutex); } printf("sub2: thread=%ld myresult=%e. Done. \\n",tid,myresult); pthread_exit(0); } int main(int argc, char *argv[]) { long t1=1, t2=2, t3=3; int i, rc; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_condvar, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, sub1, (void *)t1); pthread_create(&threads[1], &attr, sub2, (void *)t2); pthread_create(&threads[2], &attr, sub2, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final result=%e. Done.\\n", 3,finalresult); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_condvar); pthread_exit (0); }
1
#include <pthread.h> void *producer(),*consumer(); int *array; int limit=-1; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int main(int argc, char **argv) { int howmany; pthread_t johntid,marytid; long long *howlong; howmany=atoi(argv[1]); array=calloc(howmany,sizeof(int)); pthread_create(&marytid,0, consumer, &howmany); pthread_create(&johntid,0, producer, &howmany); pthread_join(johntid,0); pthread_join(marytid,(void **)&howlong); printf("John and Mary Threads done with wait %lld\\n",*howlong); } void * producer(int *howmany) { int i; for (i=0;i<*howmany;i++) { array[i]=i; if (!i%1000) { pthread_mutex_lock(&mtx); limit=i; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); } } pthread_mutex_lock(&mtx); limit=i-1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); printf("John produced %d Numbers\\n",*howmany); pthread_exit(0); } void *consumer(int *howmany) { int i,mylimit; long long sum=0; long long *wait; wait =malloc (sizeof (long long)); *wait=0; i=0; while (i< *howmany) { pthread_mutex_lock(&mtx); while (mylimit == limit) { (*wait)++; pthread_cond_wait(&cond,&mtx); } mylimit=limit; pthread_mutex_unlock(&mtx); while (i<=mylimit) sum+=array[i++]; } printf("Mary consumed %d Numbers for a total of %lld\\n",*howmany,sum); pthread_exit(wait); }
0
#include <pthread.h> extern pthread_mutex_t printf_lock; extern pthread_mutex_t setup_lock; extern pthread_mutex_t chairs_lock; extern sem_t TA_ready; extern sem_t TA_done; extern sem_t Student_register; extern int setupNotDone; extern int globalSeed; extern int occupied_chairs; extern int MAX_CHAIRS; extern int chairs[]; extern int front; extern int rear; int generateSomeTime(int, unsigned int*); void* TA(void* param) { unsigned int seed = globalSeed; globalSeed++; printf("TA summoned.\\n"); pthread_mutex_unlock(&setup_lock); while(1) { pthread_mutex_lock(&chairs_lock); if (occupied_chairs == 0) printf("No students waiting, TA will sleep:)\\n"); pthread_mutex_unlock(&chairs_lock); sem_wait(&Student_register); pthread_mutex_lock(&chairs_lock); occupied_chairs--; int SID = chairs[front]; front++; front = front%MAX_CHAIRS; int time = generateSomeTime(0, &seed); printf("TA will help SID: %d for %d seconds.\\n", SID , time); pthread_mutex_unlock(&chairs_lock); sleep(time); printf("SID:%d done with TA\\n", SID); sem_post(&TA_done); sem_post(&TA_ready); } pthread_exit(0); }
1
#include <pthread.h> int nitems; struct { pthread_mutex_t mutex; int buff[1000000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; }nready = { PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER }; void *produce(void*); void *consume(void*); int main(int argc,char *argv[]) { int i,nthreads,count[100]; pthread_t tid_produce[100],tid_consume; if(argc != 3) { exit(0); } nitems = atoi(argv[1]); nthreads = atoi(argv[2]); printf("****************************\\n"); printf("shared npt:%d nval:%d \\n", shared.nput, shared.nval); printf("nready nready:%d\\n", nready.nready); printf("****************************\\n"); printf("func:%s line:%d nitems:%d nthreads:%d **********\\n", __func__, 49, nitems, nthreads); pthread_setconcurrency(nthreads+1); printf("func:%s line:%d creat produce nthreads:%d **********\\n", __func__, 52, nthreads); for(i=0;i<nthreads;++i) { count[i] = 0; pthread_create(&tid_produce[i],0,produce,&count[i]); } printf("func:%s line:%d create consume **********\\n", __func__, 59); pthread_create(&tid_consume,0,consume,0); for(i=0;i<nthreads;i++) { pthread_join(tid_produce[i],0); printf("count[%d] = %d\\n",i,count[i]); } pthread_join(tid_consume,0); exit(0); } void *produce(void *arg) { int src = (*(int*)arg); printf("func :%s line:%d arg:%d producer begins work\\n", __func__, 78 , src); for(; ;) { pthread_mutex_lock(&shared.mutex); if(shared.nput >= nitems) { printf("func:%s line:%d nput >= nitems\\n", __func__, 84); pthread_mutex_unlock(&shared.mutex); return ; } shared.buff[shared.nput] = shared.nval; shared.nput++; shared.nval++; pthread_mutex_unlock(&shared.mutex); pthread_mutex_lock(&nready.mutex); if(nready.nready == 0) pthread_cond_signal(&nready.cond); nready.nready++; pthread_mutex_unlock(&nready.mutex); *((int*) arg) += 1; } } void *consume(void *arg) { int i; int src = (int)(arg); printf("func:%s line:%d arg:%d consuemer begins work.\\n", __func__, 105, src); for(i=0;i<nitems;i++) { pthread_mutex_lock(&nready.mutex); while(nready.nready == 0) pthread_cond_wait(&nready.cond,&nready.mutex); nready.nready--; printf("func:%s line:%d nready:%d\\n", __func__, 112, nready.nready); pthread_mutex_unlock(&nready.mutex); if(shared.buff[i] != i) printf("buff[%d] = %d\\n",i,shared.buff[i]); } return; }
0
#include <pthread.h> void *philosopher (void *id); void grab_chopstick (int, int, char *); void down_chopsticks (int, int); int food_on_table (); int get_token (); void return_token (); pthread_mutex_t chopstick[5]; pthread_t philo[5]; pthread_mutex_t food_lock; int sleep_seconds = 0; sem_t num_can_eat_sem; int main (int argn, char **argv) { int i; pthread_mutex_init (&food_lock, 0); sem_init(&num_can_eat_sem, 0, 5 - 1); for (i = 0; i < 5; i++) pthread_mutex_init (&chopstick[i], 0); for (i = 0; i < 5; i++) pthread_create (&philo[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (philo[i], 0); return 0; } void * philosopher (void *num) { int id; int i, left_chopstick, right_chopstick, f; id = (int)num; printf ("Philosopher %d is done thinking and now ready to eat.\\n", id); right_chopstick = id; left_chopstick = id + 1; if (left_chopstick == 5) left_chopstick = 0; while (f = food_on_table ()) { get_token (); grab_chopstick (id, right_chopstick, "right "); grab_chopstick (id, left_chopstick, "left"); printf ("Philosopher %d: eating.\\n", id); usleep (5000 * (100 - f + 1)); down_chopsticks (left_chopstick, right_chopstick); return_token (); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table () { static int food = 100; int myfood; pthread_mutex_lock (&food_lock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&food_lock); return myfood; } void grab_chopstick (int phil, int c, char *hand) { pthread_mutex_lock (&chopstick[c]); printf ("Philosopher %d: got %s chopstick %d\\n", phil, hand, c); } void down_chopsticks (int c1, int c2) { pthread_mutex_unlock (&chopstick[c1]); pthread_mutex_unlock (&chopstick[c2]); } int get_token () { sem_wait(&num_can_eat_sem); } void return_token () { sem_post(&num_can_eat_sem); }
1
#include <pthread.h> int mutateeCplusplus = 0; const char *Builder_id=""; { pthread_t tid; int is_in_instr; } thrds_t; thrds_t thrds[8]; pthread_mutex_t barrier_mutex; pthread_mutex_t count_mutex; volatile int times_level1_called; void my_barrier(volatile int *br) { int n_sleeps = 0; pthread_mutex_lock(&barrier_mutex); (*br)++; if (*br == 8) *br = 0; pthread_mutex_unlock(&barrier_mutex); while (*br) { if (n_sleeps++ == 10) { fprintf(stderr, "[%s:%u] - Not all threads reported. Perhaps " "tramp guards are incorrectly preventing some threads " "from running\\n", "test14.mutatee.c", 52); exit(1); } sleep(1); } } int level3(int volatile count) { static volatile int prevent_optimization; if (!count) return 0; level3(count-1); prevent_optimization++; return prevent_optimization + count; } void level2() { level3(100); } void level1() { unsigned i; static int bar, bar2; pthread_t me = pthread_self(); for (i=0; i<8; i++) if (thrds[i].tid == me) break; if (i == 8) { fprintf(stderr, "[%s:%d] - Error, couldn't find thread id %lu\\n", "test14.mutatee.c", 96, me); exit(1); } if (thrds[i].is_in_instr) { fprintf(stderr, "[%s:%d] - Error, thread %lu reentered instrumentation\\n", "test14.mutatee.c", 102, me); exit(1); } thrds[i].is_in_instr = 1; pthread_mutex_lock(&count_mutex); times_level1_called++; pthread_mutex_unlock(&count_mutex); my_barrier(&bar); level2(); my_barrier(&bar2); thrds[i].is_in_instr = 0; } void level0(int count) { if (count) level0(count - 1); } volatile unsigned ok_to_go = 0; void *init_func(void *arg) { assert(arg == 0); while(! ok_to_go) sleep(1); level0(4 -1); return 0; } int attached_fd; void parse_args(int argc, char *argv[]) { int i; for (i=0; i<argc; i++) { if (strstr(argv[i], "-attach")) { if (++i == argc) break; attached_fd = atoi(argv[i]); } } } int isAttached = 0; int checkIfAttached() { return isAttached; } int main(int argc, char *argv[]) { unsigned i; void *ret_val; char c = 'T'; pthread_attr_t attr; if(argc == 1) { printf("Mutatee %s [%s]:\\"%s\\"\\n", argv[0], mutateeCplusplus ? "C++" : "C", Builder_id); return 0; } pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier_mutex, 0); pthread_mutex_init(&count_mutex, 0); parse_args(argc, argv); for (i=1; i<8; i++) { pthread_create(&(thrds[i].tid), &attr, init_func, 0); thrds[i].is_in_instr = 0; } thrds[0].tid = pthread_self(); thrds[0].is_in_instr = 0; if (attached_fd) { if (write(attached_fd, &c, sizeof(char)) != sizeof(char)) { fprintf(stderr, "*ERROR*: Writing to pipe\\n"); exit(-1); } close(attached_fd); printf("Waiting for mutator to attach...\\n"); while (!checkIfAttached()) ; printf("Mutator attached. Mutatee continuing.\\n"); } ok_to_go = 1; init_func(0); for (i=1; i<8; i++) { pthread_join(thrds[i].tid, &ret_val); } if (times_level1_called != 8*4) { fprintf(stderr, "[%s:%u] - level1 called %u times. Expected %u\\n", "test14.mutatee.c", 213, times_level1_called, 8*4); exit(1); } return 0; }
0
#include <pthread.h> pthread_mutex_t m, l; int A = 0, B = 0; void *t1(void *arg) { pthread_mutex_lock(&m); A++; if (A == 1) pthread_mutex_lock(&l); pthread_mutex_unlock(&m); pthread_mutex_lock(&m); A--; if (A == 0) pthread_mutex_unlock(&l); pthread_mutex_unlock(&m); } void *t2(void *arg) { pthread_mutex_lock(&m); B++; if (B == 1) pthread_mutex_lock(&l); pthread_mutex_unlock(&m); pthread_mutex_lock(&m); B--; if (B == 0) pthread_mutex_unlock(&l); pthread_mutex_unlock(&m); } void *t3(void *arg) { } void *t4(void *arg) { } int main(void) { pthread_mutex_init(&m,0); pthread_mutex_init(&l,0); pthread_t a1, a2, b1, b2; pthread_create(&a1, 0, t1, 0); pthread_create(&b1, 0, t2, 0); pthread_create(&a2, 0, t3, 0); pthread_create(&b2, 0, t4, 0); pthread_join(a1, 0); pthread_join(b1, 0); pthread_join(a2, 0); pthread_join(b2, 0); return 0; }
1
#include <pthread.h> int in = 0 ; int out = 0 ; int buff[10]={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<10;i++) printf("%d",buff[i]); printf("\\n"); } void *produce() { int id=++product_id; while(1) { sleep(1); sem_wait(&empty_sem); pthread_mutex_lock(&mutex); in = in%10; 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(1); sem_wait(&full_sem); pthread_mutex_lock(&mutex); out =out%10; 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,10); 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,produce,(void *)(&i)); if(ret[i]<0) { printf("product %d creation failed\\n",i); exit(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); } } for(i=0;i<2;i++) { pthread_join(id1[i],0); pthread_join(id2[i],0); } exit(0); }
0
#include <pthread.h> int nitems; struct{ pthread_mutex_t mutex; int buff[1000000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; void *produce(void *); void *consume(void *); int main(int argc, char *argv[]){ int i, nthreads, count[100]; pthread_t tid_produce[100], tid_consume; if (argc != 3){ printf("usage:produce consume"); exit(0); } nitems = atoi(argv[1]); nthreads = atoi(argv[2]); pthread_setconcurrency(nthreads); for(i=0; i<nthreads; ++i){ count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } for(i=0; i<nthreads; i++){ pthread_join(tid_produce[i], 0); printf("count[%d]=%d\\n", i, count[i]); } pthread_create(&tid_consume, 0, consume, 0); pthread_join(tid_consume, 0); exit(0); } void *produce(void *arg){ for(;;){ pthread_mutex_lock(&shared.mutex); if (shared.nput >= nitems){ pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[shared.nput] = shared.nval; shared.nput++; shared.nval++; pthread_mutex_unlock(&shared.mutex); *((int *)arg) += 1; } } void *consume(void *arg){ int i; for(i=0; i<nitems; i++){ if (shared.buff[i] != i){ printf("buff[%d] = %d\\n", i, shared.buff[i]); } } return 0; }
1
#include <pthread.h> sem_t PID_sem; bool stop = 0; double y = 0; struct udp_conn connection; pthread_mutex_t mutex; volatile int period_us = 5000; int udp_init_client(struct udp_conn *udp, int port, char *ip) { struct hostent *host; if ((host = gethostbyname(ip)) == 0) return -1; udp->client_len = sizeof(udp->client); memset((char *)&(udp->server), 0, sizeof(udp->server)); udp->server.sin_family = AF_INET; udp->server.sin_port = htons(port); bcopy((char *)host->h_addr, (char *)&(udp->server).sin_addr.s_addr, host->h_length); if ((udp->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) return udp->sock; return 0; } int udp_send(struct udp_conn *udp, char *buf, int len) { return sendto(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->server), sizeof(udp->server)); } int udp_receive(struct udp_conn *udp, char *buf, int len) { int res = recvfrom(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->client), &(udp->client_len)); return res; } void udp_close(struct udp_conn *udp) { close(udp->sock); return; } int clock_nanosleep(struct timespec *next) { struct timespec now; struct timespec sleep; clock_gettime(CLOCK_REALTIME, &now); sleep.tv_sec = next->tv_sec - now.tv_sec; sleep.tv_nsec = next->tv_nsec - now.tv_nsec; if (sleep.tv_nsec < 0) { sleep.tv_nsec += 1000000000; sleep.tv_sec -= 1; } nanosleep(&sleep, 0); return 0; } void timespec_add_us(struct timespec *t, long us) { t->tv_nsec += us*1000; if (t->tv_nsec > 1000000000) { t->tv_nsec -= 1000000000; t->tv_sec += 1; } } void* periodic_request() { struct timespec next; clock_gettime(CLOCK_REALTIME, &next); while(1){ if (stop){ break; } pthread_mutex_lock(&mutex); if (udp_send(&connection, "GET", strlen("GET") + 1) < 0){ perror("Error in sendto()"); } pthread_mutex_unlock(&mutex); timespec_add_us(&next, period_us); clock_nanosleep(&next); } printf("Exit periodic request\\n"); } void* udp_listener() { int bytes_received; char recvbuf[512]; char testbuf[512]; while(1){ if (stop){ break; } bytes_received = udp_receive(&connection, recvbuf, 512); if (bytes_received > 0){ memcpy(testbuf, recvbuf, strlen("GET_ACK:")); if (testbuf[0] == 'G'){ y = get_double(recvbuf); sem_post(&PID_sem); } } } sem_post(&PID_sem); printf("Exit udp listener\\n"); } void* PID_control() { char sendbuf[64]; double error = 0.0; double reference = 1.0; double integral = 0.0; double u = 0.0; int Kp = 10; int Ki = 800; double period_s = period_us/(1000.0*1000.0); while(1){ if (stop){ break; } sem_wait(&PID_sem); error = reference - y; integral = integral + (error*period_s); u = Kp*error + Ki*integral; snprintf(sendbuf, sizeof sendbuf, "SET:%f", u); pthread_mutex_lock(&mutex); if (udp_send(&connection, sendbuf, strlen(sendbuf)+1) < 0){ perror("Error in sendto()"); } pthread_mutex_unlock(&mutex); } printf("Exit PID controller\\n"); } double get_double(const char *str) { while (*str && !(isdigit(*str) || ((*str == '-' || *str == '+') && isdigit(*(str + 1))))) str++; return strtod(str, 0); } int main(void){ udp_init_client(&connection, 9999, "192.168.0.1"); if (udp_send(&connection, "START", strlen("START")+1) < 0){ perror("Error in sendto()"); } if (pthread_mutex_init(&mutex, 0) != 0) { perror("mutex initialization"); } if (sem_init(&PID_sem, 0, 1) != 0) { perror("semaphore initialization"); } pthread_t udp_listener_thread, PID_control_thread, periodic_request_thread; pthread_create(&udp_listener_thread, 0, udp_listener, 0); pthread_create(&PID_control_thread, 0, PID_control, 0); pthread_create(&periodic_request_thread, 0, periodic_request, 0); usleep(500*1000); stop = 1; if (udp_send(&connection, "STOP", strlen("STOP")) < 0){ perror("Error in sendto()"); } pthread_join(periodic_request_thread, 0); pthread_join(udp_listener_thread, 0); pthread_join(PID_control_thread, 0); pthread_mutex_destroy(&mutex); sem_destroy(&PID_sem); udp_close(&connection); return 0; }
0
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int running_flag = 0; static int stop_flag = 0; static pthread_t tid; static uint16_t timeout; static char *program_name; static uint32_t recorded_jobid = NO_VAL; static uint32_t recorded_stepid = NO_VAL; static void *monitor(void *); static int call_external_program(void); void step_terminate_monitor_start(uint32_t jobid, uint32_t stepid) { slurm_ctl_conf_t *conf; pthread_attr_t attr; pthread_mutex_lock(&lock); if (running_flag) { pthread_mutex_unlock(&lock); return; } conf = slurm_conf_lock(); if (conf->unkillable_program == 0) { slurm_conf_unlock(); pthread_mutex_unlock(&lock); return; } timeout = conf->unkillable_timeout; program_name = xstrdup(conf->unkillable_program); slurm_conf_unlock(); slurm_attr_init(&attr); pthread_create(&tid, &attr, monitor, 0); slurm_attr_destroy(&attr); running_flag = 1; recorded_jobid = jobid; recorded_stepid = stepid; pthread_mutex_unlock(&lock); return; } void step_terminate_monitor_stop(void) { pthread_mutex_lock(&lock); if (!running_flag) { pthread_mutex_unlock(&lock); return; } if (stop_flag) { error("step_terminate_monitor_stop: already stopped"); pthread_mutex_unlock(&lock); return; } stop_flag = 1; debug("step_terminate_monitor_stop signalling condition"); pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); if (pthread_join(tid, 0) != 0) { error("step_terminate_monitor_stop: pthread_join: %m"); } xfree(program_name); return; } static void *monitor(void *notused) { struct timespec ts = {0, 0}; int rc; info("monitor is running"); ts.tv_sec = time(0) + 1 + timeout; pthread_mutex_lock(&lock); if (stop_flag) goto done; rc = pthread_cond_timedwait(&cond, &lock, &ts); if (rc == ETIMEDOUT) { call_external_program(); } else if (rc != 0) { error("Error waiting on condition in monitor: %m"); } done: pthread_mutex_unlock(&lock); info("monitor is stopping"); return 0; } static int call_external_program(void) { int status, rc, opt; pid_t cpid; int max_wait = 300; int time_remaining; debug("step_terminate_monitor: unkillable after %d sec, calling: %s", timeout, program_name); if (program_name == 0 || program_name[0] == '\\0') return 0; if (access(program_name, R_OK | X_OK) < 0) { debug("step_terminate_monitor not running %s: %m", program_name); return 0; } if ((cpid = fork()) < 0) { error("step_terminate_monitor executing %s: fork: %m", program_name); return -1; } if (cpid == 0) { char *argv[2]; char buf[16]; snprintf(buf, 16, "%u", recorded_jobid); setenv("SLURM_JOBID", buf, 1); setenv("SLURM_JOB_ID", buf, 1); snprintf(buf, 16, "%u", recorded_stepid); setenv("SLURM_STEPID", buf, 1); setenv("SLURM_STEP_ID", buf, 1); argv[0] = program_name; argv[1] = 0; setpgrp(); execv(program_name, argv); error("step_terminate_monitor execv(): %m"); exit(127); } opt = WNOHANG; time_remaining = max_wait; while (1) { rc = waitpid(cpid, &status, opt); if (rc < 0) { if (errno == EINTR) continue; return 0; } else if (rc == 0) { sleep(1); if ((--time_remaining) == 0) { error("step_terminate_monitor: %s still running" " after %d seconds. Killing.", program_name, max_wait); killpg(cpid, SIGKILL); opt = 0; } } else { return status; } } }
1
#include <pthread.h> { double *a; double *b; double sum; int vec_len; } DD; DD dotstr; pthread_t callThd[4]; pthread_mutex_t mutex_sum; void *dotprod(void *arg) { int i, start, end, len; long offset = (long)arg; double mysum, *x, *y; len = dotstr.vec_len; 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]) + pow(1,0) ; } pthread_mutex_lock(&mutex_sum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: Local Sum=%f Current Global Sum=%f\\n", offset, start, end, mysum, dotstr.sum); pthread_mutex_unlock(&mutex_sum); pthread_exit((void *)0); } int main(int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double *)malloc(4 * 125 * sizeof(double)); b = (double *)malloc(4 * 125 * sizeof(double)); a[0] = 0.5; b[0] = 0.25; for (i = 1; i < 125 * 4; i++) { a[i] = 0; b[i] = 0; } for (i = 1; i < 125 * 4; i++) { a[i] = a[i - 1] + 0.5; b[i] = b[i - 1] + 0.25; } dotstr.vec_len = 125; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutex_sum, 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(&mutex_sum); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t Mtx; int Global; void *Thread2(void *x) { barrier_wait(&barrier); pthread_mutex_lock(&Mtx); Global = 43; pthread_mutex_unlock(&Mtx); return 0; } void *Thread1(void *x) { pthread_mutex_init(&Mtx, 0); pthread_mutex_lock(&Mtx); Global = 42; pthread_mutex_unlock(&Mtx); barrier_wait(&barrier); return 0; } int main() { barrier_init(&barrier, 2); pthread_t t[2]; pthread_create(&t[0], 0, Thread1, 0); pthread_create(&t[1], 0, Thread2, 0); pthread_join(t[0], 0); pthread_join(t[1], 0); pthread_mutex_destroy(&Mtx); return 0; }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; void main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 != 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount1: %d\\n",count); pthread_cond_signal( &condition_var ); if ( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 == 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount2: %d\\n",count); pthread_cond_signal( &condition_var ); if( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } }
0
#include <pthread.h> int q[4]; 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 < 4) { 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 < 4); 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> int enqueue_element(struct queue *q, void *data) { struct queue_element *tmp = malloc(sizeof(struct queue_element)); if(!tmp) return ENQUEUE_FAILED; pthread_mutex_lock(q->lock); q->tail->data = data; q->tail->next = tmp; q->enqueued++; q->tail = tmp; pthread_mutex_unlock(q->lock); eventfd_write(q->eventfd, 1ULL); if((q->enqueued - q->dequeued) > q->threshold) return ENQUEUE_FILLING_FAST; else return ENQUEUE_SUCCESS; } void *dequeue_element(struct queue *q) { struct queue_element *tmp; void *data; uint64_t junk; if(q->head == q->tail) return 0; if(eventfd_read(q->eventfd, &junk) == -1) return 0; pthread_mutex_lock(q->lock); tmp = q->head; data = tmp->data; q->head = tmp->next; q->dequeued++; pthread_mutex_unlock(q->lock); free(tmp); return data; } int enqueue_element_lockless(struct queue *q, void *data) { struct queue_element *tmp = malloc(sizeof(struct queue_element)); if(!tmp) return ENQUEUE_FAILED; q->tail->data = data; q->tail->next = tmp; q->enqueued++; q->tail = tmp; eventfd_write(q->eventfd, 1ULL); if((q->enqueued - q->dequeued) > q->threshold) return ENQUEUE_FILLING_FAST; else return ENQUEUE_SUCCESS; } void *dequeue_element_lockless(struct queue *q) { struct queue_element *tmp; void *data; uint64_t junk; if(q->head == q->tail) return 0; eventfd_read(q->eventfd, &junk); tmp = q->head; data = tmp->data; q->head = tmp->next; free(tmp); q->dequeued++; return data; } struct queue *create_queue(int flag, int threshold, int id) { struct queue *q; if(flag != FLAG_QUEUE_WITHOUT_LOCK && flag != FLAG_QUEUE_WITH_LOCK) return 0; q = malloc(sizeof(struct queue)); if(!q) return 0; memset(q, 0, sizeof(struct queue)); q->threshold = threshold; q->index = id; if(flag == FLAG_QUEUE_WITH_LOCK){ q->enqueue = enqueue_element; q->dequeue = dequeue_element; q->lock = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(q->lock, 0); }else { q->enqueue = enqueue_element_lockless; q->dequeue = dequeue_element_lockless; } q->head = q->tail = malloc(sizeof(struct queue_element)); if(!q->head) goto exit1; q->eventfd = eventfd(0, EFD_NONBLOCK|EFD_SEMAPHORE); if(q->eventfd == -1) goto exit2; return q; exit2: free(q->head); exit1: free(q); return 0; } void delete_queue(struct queue *q) { struct queue_element *tmp; while(q->head != 0){ tmp = q->head->next; free(q->head); q->head = tmp; } close(q->eventfd); free(q); return; }
0
#include <pthread.h> int q[4]; 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 < 4) { 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 < 4); 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[3]; int sorted[3]; void producer () { int i, idx; for (i = 0; i < 3; i++) { idx = findmaxidx (source, 3); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 3; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 3; 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> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void* inc_count(void* t) { int i; long my_id = (long)t; for (i=0; i<10; ++i) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf( "inc_count(): thread %ld, count = %d Threshold reached...\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex...\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void* watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); } count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char* argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); rc = pthread_create(&threads[0], &attr, watch_count, (void*)t1); if (rc) { printf("Creating watch_count thread failed!! [%d]\\n", rc); exit(-1); } rc = pthread_create(&threads[1], &attr, inc_count, (void*)t2); if (rc) { printf("Creating first inc_count thread failed!! [%d]\\n", rc); exit(-1); } pthread_create(&threads[2], &attr, inc_count, (void*)t3); if (rc) { printf("Creating second inc_count thread failed!! [%d]\\n", rc); exit(-1); } for (i=0; i<3; ++i) { pthread_join(threads[i], 0); } printf("Main(): Waited on %d threads, Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int num_pthreads; double c_x_min; double c_x_max; double c_y_min; double c_y_max; double pixel_width; double pixel_height; int iteration_max = 200; int image_size; unsigned char **image_buffer; int i_x_max; int i_y_max; int image_buffer_size; int current_pixel; int gradient_size = 16; int colors[17][3] = { {66, 30, 15}, {25, 7, 26}, {9, 1, 47}, {4, 4, 73}, {0, 7, 100}, {12, 44, 138}, {24, 82, 177}, {57, 125, 209}, {134, 181, 229}, {211, 236, 248}, {241, 233, 191}, {248, 201, 95}, {255, 170, 0}, {204, 128, 0}, {153, 87, 0}, {106, 52, 3}, {16, 16, 16}, }; void allocate_image_buffer(){ int rgb_size = 3; image_buffer = (unsigned char **) malloc(sizeof(unsigned char *) * image_buffer_size); for(int i = 0; i < image_buffer_size; i++){ image_buffer[i] = (unsigned char *) malloc(sizeof(unsigned char) * rgb_size); }; }; void init(int argc, char *argv[]){ if(argc < 6){ printf("usage: ./mandelbrot_pth c_x_min c_x_max c_y_min c_y_max image_size\\n"); printf("examples with image_size = 11500:\\n"); printf(" Full Picture: ./mandelbrot_pth -2.5 1.5 -2.0 2.0 11500\\n"); printf(" Seahorse Valley: ./mandelbrot_pth -0.8 -0.7 0.05 0.15 11500\\n"); printf(" Elephant Valley: ./mandelbrot_pth 0.175 0.375 -0.1 0.1 11500\\n"); printf(" Triple Spiral Valley: ./mandelbrot_pth -0.188 -0.012 0.554 0.754 11500\\n"); exit(0); } else{ sscanf(argv[1], "%lf", &c_x_min); sscanf(argv[2], "%lf", &c_x_max); sscanf(argv[3], "%lf", &c_y_min); sscanf(argv[4], "%lf", &c_y_max); sscanf(argv[5], "%d", &image_size); i_x_max = image_size; i_y_max = image_size; image_buffer_size = image_size * image_size; pixel_width = (c_x_max - c_x_min) / i_x_max; pixel_height = (c_y_max - c_y_min) / i_y_max; num_pthreads = atoi(getenv("PTH_NUM_THREADS")); }; }; void update_rgb_buffer(int iteration, int x, int y){ int color; if(iteration == iteration_max){ image_buffer[(i_y_max * y) + x][0] = colors[gradient_size][0]; image_buffer[(i_y_max * y) + x][1] = colors[gradient_size][1]; image_buffer[(i_y_max * y) + x][2] = colors[gradient_size][2]; } else{ color = iteration % gradient_size; image_buffer[(i_y_max * y) + x][0] = colors[color][0]; image_buffer[(i_y_max * y) + x][1] = colors[color][1]; image_buffer[(i_y_max * y) + x][2] = colors[color][2]; }; }; void write_to_file(){ FILE * file; char * filename = "output_pth.ppm"; int max_color_component_value = 255; file = fopen(filename,"wb"); fprintf(file, "P6\\n %s\\n %d\\n %d\\n %d\\n", comment, i_x_max, i_y_max, max_color_component_value); for(int i = 0; i < image_buffer_size; i++){ fwrite(image_buffer[i], 1 , 3, file); }; fclose(file); }; void *compute_mandelbrot_thread(void *pthreadid) { double z_x; double z_y; double z_x_squared; double z_y_squared; double escape_radius_squared = 4; int iteration; int i_x; int i_y; int i; double c_x; double c_y; int i_k; while(1){ pthread_mutex_lock(&mutex); i_k = current_pixel; current_pixel += 8; pthread_mutex_unlock(&mutex); for (i = 0; i < 8; i++) { if (i_k >= i_y_max * i_x_max) pthread_exit(0); i_y = i_k / i_x_max; c_y = c_y_min + i_y * pixel_height; if(fabs(c_y) < pixel_height / 2){ c_y = 0.0; } i_x = i_k % i_x_max; c_x = c_x_min + i_x * pixel_width; z_x = 0.0; z_y = 0.0; z_x_squared = 0.0; z_y_squared = 0.0; for(iteration = 0; iteration < iteration_max && ((z_x_squared + z_y_squared) < escape_radius_squared); iteration++){ z_y = 2 * z_x * z_y + c_y; z_x = z_x_squared - z_y_squared + c_x; z_x_squared = z_x * z_x; z_y_squared = z_y * z_y; }; update_rgb_buffer(iteration, i_x, i_y); i_k++; } } } void compute_mandelbrot(){ pthread_t *threads; int i; int error_code; threads = (pthread_t *) malloc(sizeof(pthread_t) * num_pthreads); current_pixel = 0; for (i = 0; i < num_pthreads; i++) { error_code = pthread_create(&threads[i], 0, compute_mandelbrot_thread, 0); if (error_code){ printf("ERROR pthread_create(): %d\\n", error_code); exit(-1); } } for(i = 0; i < num_pthreads; i++) { error_code = pthread_join(threads[i], 0); if (error_code) { printf("ERROR; return code from pthread_join() is %d\\n", error_code); exit(-1); } } pthread_mutex_destroy(&mutex); }; int main(int argc, char *argv[]){ init(argc, argv); allocate_image_buffer(); compute_mandelbrot(); write_to_file(); return 0; };
1
#include <pthread.h>extern void __VERIFIER_error() ; extern void __VERIFIER_assume(int expr); extern int __VERIFIER_nondet_int(void); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } void *compute_pi (void *); double intervalWidth, intervalMidPoint, area = 0.0; int numberOfIntervals, interval, iCount,iteration, num_threads; double distance=0.5,four=4.0; pthread_mutex_t area_mutex=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t pi_mutex=PTHREAD_MUTEX_INITIALIZER; void myPartOfCalc(int myID) { int myInterval; double myIntervalMidPoint, myArea = 0.0, result; for (myInterval = myID + 1; myInterval <= numberOfIntervals; myInterval += numberOfIntervals) { myIntervalMidPoint = ((double) myInterval - distance) * intervalWidth; myArea += (four / (1.0 + myIntervalMidPoint * myIntervalMidPoint)); } result = myArea * intervalWidth; pthread_mutex_lock(&area_mutex); area += result; pthread_mutex_unlock(&area_mutex); } int main(int argc, char *argv[]) { int i,Iteration,ret_count; pthread_t p_threads[8]; pthread_t * threads; pthread_attr_t pta; pthread_attr_t attr; double computed_pi,diff; FILE *fp; int CLASS_SIZE,THREADS; char * CLASS; ret_count=pthread_mutex_init(&area_mutex,0); if (ret_count) { exit(-1); } printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)"); printf("\\n\\t\\t Email : hpcfte@cdac.in"); printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Objective : PI Computations"); printf("\\n\\t\\t Computation of PI using Numerical Integration Method "); printf("\\n\\t\\t..........................................................................\\n"); numberOfIntervals = __VERIFIER_nondet_int(); if(numberOfIntervals > 8) { printf("\\n Number Of Intervals should be less than or equal to 8.Aborting\\n"); return 0; } num_threads = numberOfIntervals ; printf("\\n\\t\\t Input Parameters :"); printf("\\n\\t\\t Number Of Intervals : %d ",numberOfIntervals); ret_count=pthread_attr_init(&pta); if(ret_count) { exit(-1); } __VERIFIER_assume(numberOfIntervals>0); threads = (pthread_t *) malloc(sizeof(pthread_t) * numberOfIntervals); intervalWidth = 1.0 / (double) numberOfIntervals; for (iCount = 0; iCount < num_threads; iCount++) { ret_count=pthread_create(&threads[iCount], &pta, (void *(*) (void *)) myPartOfCalc, (void *) iCount); if (ret_count) { exit(-1); } } for (iCount = 0; iCount < numberOfIntervals; iCount++) { ret_count=pthread_join(threads[iCount], 0); if (ret_count) { exit(-1); } } ret_count=pthread_attr_destroy(&pta); if (ret_count) { exit(-1); } printf("\\n\\t\\t Computation Of PI value Using Numerical Integration Method ......Done\\n"); printf("\\n\\t\\t Computed Value Of PI : %lf", area); __VERIFIER_assert(area - 3.14159265388372456789123456789456 < 1.0E-5 || 3.14159265388372456789123456789456 - area < 1.0E-5); printf("\\n\\t\\t..........................................................................\\n"); free(threads); return 0; }
0
#include <pthread.h> char buf[128]; size_t pos; size_t len; int write_closed; pthread_mutex_t mutex; pthread_cond_t nonempty; pthread_cond_t nonfull; } bbuffer; bbuffer* bbuffer_new(void) { bbuffer* bb = (bbuffer*) malloc(sizeof(bbuffer)); bb->pos = 0; bb->len = 0; bb->write_closed = 0; pthread_mutex_init(&bb->mutex, 0); pthread_cond_init(&bb->nonempty, 0); pthread_cond_init(&bb->nonfull, 0); return bb; } ssize_t bbuffer_write(bbuffer* bb, const char* buf, size_t sz) { size_t pos = 0; pthread_mutex_lock(&bb->mutex); assert(!bb->write_closed); while (pos < sz) { size_t bb_index = (bb->pos + bb->len) % sizeof(bb->buf); size_t ncopy = sz - pos; if (ncopy > sizeof(bb->buf) - bb_index) { ncopy = sizeof(bb->buf) - bb_index; } if (ncopy > sizeof(bb->buf) - bb->len) { ncopy = sizeof(bb->buf) - bb->len; } memcpy(&bb->buf[bb_index], &buf[pos], ncopy); bb->len += ncopy; pos += ncopy; if (ncopy == 0) { if (pos > 0) { break; } pthread_cond_wait(&bb->nonfull, &bb->mutex); } } pthread_mutex_unlock(&bb->mutex); if (pos == 0 && sz > 0) { return -1; } else { if (pos > 0) { pthread_cond_broadcast(&bb->nonempty); } return pos; } } ssize_t bbuffer_read(bbuffer* bb, char* buf, size_t sz) { size_t pos = 0; pthread_mutex_lock(&bb->mutex); while (pos < sz) { size_t ncopy = sz - pos; if (ncopy > sizeof(bb->buf) - bb->pos) { ncopy = sizeof(bb->buf) - bb->pos; } if (ncopy > bb->len) { ncopy = bb->len; } memcpy(&buf[pos], &bb->buf[bb->pos], ncopy); bb->pos = (bb->pos + ncopy) % sizeof(bb->buf); bb->len -= ncopy; pos += ncopy; if (ncopy == 0) { if (bb->write_closed || pos > 0) { break; } pthread_cond_wait(&bb->nonempty, &bb->mutex); } } int write_closed = bb->write_closed; pthread_mutex_unlock(&bb->mutex); if (pos == 0 && sz > 0 && !write_closed) { return -1; } else { if (pos > 0) { pthread_cond_broadcast(&bb->nonfull); } return pos; } } void bbuffer_shutdown_write(bbuffer* bb) { pthread_mutex_lock(&bb->mutex); bb->write_closed = 1; pthread_mutex_unlock(&bb->mutex); } void* writer_threadfunc(void* arg) { const char message[] = "Hello world!\\n"; const size_t message_len = strlen(message); bbuffer* bb = (bbuffer*) arg; for (int i = 0; i != 1000000; ++i) { size_t pos = 0; while (pos < message_len) { ssize_t nwritten = bbuffer_write(bb, &message[pos], message_len - pos); if (nwritten > -1) { pos += nwritten; } } } bbuffer_shutdown_write(bb); return 0; } void* reader_threadfunc(void* arg) { bbuffer* bb = (bbuffer*) arg; char buf[1024]; ssize_t nread; while ((nread = bbuffer_read(bb, buf, sizeof(buf))) != 0) { if (nread > -1) { fwrite(buf, 1, nread, stdout); } } return 0; } int main() { bbuffer* bb = bbuffer_new(); pthread_t reader, writer; pthread_create(&reader, 0, reader_threadfunc, (void*) bb); pthread_create(&writer, 0, writer_threadfunc, (void*) bb); pthread_join(reader, 0); pthread_join(writer, 0); }
1
#include <pthread.h> struct timespec ts; pthread_mutex_t chopstick_mutex[5]; pthread_cond_t chopstick_conds[5]; int philo_states[5]; int phil_to_chopstick(int phil_id, direction_t d){ return (phil_id + d) % 5; } int chopstick_to_phil(int stick_id, direction_t d){ return (stick_id + 5 - d) % 5; } int left_of_phil(int phil_id) { return ((phil_id + (5 - 1)) % 5); } int right_of_phil(int phil_id) { return ((phil_id + 1) % 5); } void update_philo_state(int phil_id) { int left = left_of_phil(phil_id); int right = right_of_phil(phil_id); if (philo_states[phil_id] == 2 && philo_states[left] != 3 && philo_states[right] != 3) { philo_states[phil_id] = 3; pthread_cond_broadcast(&chopstick_conds[phil_id]); } } void pickup_one_chopstick(int stick_id, int phil_id){ printf("Philosopher %d picks up chopstick %d \\n", phil_id, stick_id); fflush(stdout); } void putdown_one_chopstick(int stick_id, int phil_id){ printf("Philosopher %d puts down chopstick %d \\n", phil_id, stick_id); fflush(stdout); } void pickup_chopsticks(int phil_id){ pthread_mutex_lock(&chopstick_mutex[phil_id]); philo_states[phil_id] = 2; pthread_mutex_unlock(&chopstick_mutex[phil_id]); update_philo_state(phil_id); pthread_mutex_lock(&chopstick_mutex[phil_id]); while(philo_states[phil_id] == 2) { pthread_cond_wait(&chopstick_conds[phil_id],&chopstick_mutex[phil_id]); } pthread_mutex_unlock(&chopstick_mutex[phil_id]); pickup_one_chopstick(phil_to_chopstick(phil_id, left), phil_id); pickup_one_chopstick(phil_to_chopstick(phil_id, right), phil_id); } void putdown_chopsticks(int phil_id){ putdown_one_chopstick(phil_to_chopstick(phil_id, left),phil_id); putdown_one_chopstick(phil_to_chopstick(phil_id, right),phil_id); pthread_mutex_lock(&chopstick_mutex[phil_id]); philo_states[phil_id] = 1; pthread_mutex_unlock(&chopstick_mutex[phil_id]); update_philo_state(left_of_phil(phil_id)); update_philo_state(right_of_phil(phil_id)); } double const thinking_to_eating = 0.02; double const eating_to_thinking = 0.05; void eat(int phil_id){ fprintf(stdout,"Philosopher %d eats\\n", phil_id); while (rand() / (32767 + 1.0) >= eating_to_thinking); } void think(int phil_id){ fprintf(stdout,"Philosopher %d thinks\\n", phil_id); while (rand() / (32767 + 1.0) >= thinking_to_eating); } pthread_mutex_t servings_mutex; int servings; void* philosodine(void* arg){ intptr_t phil_id; phil_id = (intptr_t) arg; while(1){ pthread_mutex_lock(&servings_mutex); if(servings <= 0){ pthread_mutex_unlock(&servings_mutex); break; } else{ servings--; pthread_mutex_unlock(&servings_mutex); } pickup_chopsticks(phil_id); eat(phil_id); putdown_chopsticks(phil_id); think(phil_id); } return 0; } int main(){ long i; pthread_t phil_threads[5]; srand(time(0)); pthread_mutex_init(&servings_mutex, 0); servings = 1000; for(i = 0; i < 5; i++) { pthread_mutex_init(&chopstick_mutex[i], 0); pthread_cond_init(&chopstick_conds[i],0); philo_states[i] = 1; } for(i = 0; i < 5; i++) pthread_create(&phil_threads[i], 0, philosodine, (void*) i); for(i = 0; i < 5; i++) pthread_join(phil_threads[i], 0); for(i = 0; i < 5; i++) { pthread_mutex_destroy(&chopstick_mutex[i]); pthread_cond_destroy(&chopstick_conds[i]); } return 0; }
0
#include <pthread.h> int brashno = 1000; int masa[4]; pthread_mutex_t lock; void* Mama(){ int position = 0; while(brashno) { int mama_get_brashno = rand() % 100 + 1; if(mama_get_brashno > brashno){ mama_get_brashno = brashno; } brashno -= mama_get_brashno; while(masa[position] == 1){ int wtime = rand() % 100 + 1; usleep(wtime*1000); } printf("MAMA PRAI PASTI4KA!\\n"); usleep(mama_get_brashno*1000); pthread_mutex_lock(&lock); masa[position] = 1; pthread_mutex_unlock(&lock); if(position == 3) { position = 0; } else { position++; } } } void* Ivan(){ int position = 0; while(brashno){ while(masa[position] == 0) { int wtime = rand() % 100 + 1; usleep(wtime*1000); } pthread_mutex_lock(&lock); masa[position] =0; pthread_mutex_unlock(&lock); printf("IVAN4O LAPA PASTI4KAAA!\\n"); if(position == 3) { position = 0; } else { position++; } } } int main(){ pthread_mutex_init(&lock,0); pthread_t thread[2]; pthread_create(&thread[0],0,Mama,0); pthread_create(&thread[1],0,Ivan,0); pthread_join(thread[1],0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> void mifuncion(int *numero); int VARIABLE_GLOBAL; pthread_mutex_t MXVARGLOBAL; int main(void) { int i; int hilos = 3; pthread_t tid[hilos][2]; pthread_mutex_init(&MXVARGLOBAL, 0); for (i = 0; i < hilos; i++) { tid[i][1] = i+1; pthread_create(&tid[i][0], 0, (void*) mifuncion, &tid[i][1]); } for (i = 0; i < hilos; i++) { pthread_join(tid[i][0], 0); } printf("\\n\\n Main: Terminaron todos los hilos\\n\\tVARIABLE_GLOBAL: %d\\n\\n", VARIABLE_GLOBAL); pthread_mutex_destroy(&MXVARGLOBAL); return 0; } void mifuncion(int *numero) { int i; for (i = 0; i < 10000; i++) { pthread_mutex_lock(&MXVARGLOBAL); VARIABLE_GLOBAL++; printf("Hilo %d - VARIABLE_GLOBAL: %d\\n", *numero, VARIABLE_GLOBAL); fflush(stdout); pthread_mutex_unlock(&MXVARGLOBAL); } printf("Hilo %d - %d TERMINE!\\n\\n", *numero, i); fflush(stdout); }
0
#include <pthread.h> const int GAME_PORT = 6967; int sockfd, connfd; struct sockaddr_in serv_addr, client; pthread_t worker; pthread_mutex_t enemy_mutex,ball_mutex; void host_init(); void client_init(); void logic_init() { if (is_host) { host_init(); } else { client_init(); } } void logic_cleanup(){ } void update_enemy_coord(float x, float y) { pthread_mutex_lock(&enemy_mutex); enemy_x = x; enemy_y = y; pthread_mutex_unlock(&enemy_mutex); } void update_ball_coord(float x, float y, float z) { pthread_mutex_lock(&ball_mutex); ball_x = x; ball_y = y; ball_z = z; pthread_mutex_unlock(&ball_mutex); } void* server_thread(void* in) { char client_message[1000], reply[1000]; int read_size; listen(sockfd,3); puts("Waiting for incoming connections...\\n"); while (1) { puts("THIS IS FUCKING AMAZING!!!!!"); connfd = accept(sockfd, (struct sockaddr*)0, 0); if(connfd < 0) { puts("FAILEDDDDDDDDDDDDDDDDDD"); die("Problem accepting connection. \\n"); continue; } else { puts("Connection accepted. \\n"); while( (read_size = recv(connfd , client_message , 2000 , 0)) > 0 ) { printf("This is the client's message: %s\\n",client_message); int n = sprintf(reply, "%f,%f,%f,%f,%f \\n", player_x, player_y, ball_x, ball_y, ball_z); write(connfd , reply , n); } if(read_size == 0) { puts("Client disconnected \\n"); fflush(stdout); } else if(read_size == -1) { puts("FAILEDDDDDDDDDDDDDDDDDD"); perror("recv failed \\n"); } } } } void host_init() { sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(GAME_PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr))) { perror("bind failed. Error"); } puts("Bind done"); pthread_create(&worker, (void*) 0, server_thread, 0); } void* client_thread(void* in) { char message[1000] , server_reply[1000]; sleep(1); if (connect(sockfd , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0) { puts("FAILEDDDDDDDDDDDDDDDDDD"); perror("connect failed. Error \\n"); return 0; } printf("Connected. \\n"); while(1) { int n = sprintf(message, "%f,%f, \\n", player_x, player_y); if(send(sockfd, message,strlen(message),0) < 0) { puts("FAILEDDDDDDDDDDDDDDDDDD"); die("Send failed \\n"); return 0; } if( recv(sockfd, server_reply , 2000 , 0) < 0) { puts("FAILEDDDDDDDDDDDDDDDDDD"); die("recv failed \\n"); break; } else { float new_enemyx, new_enemyy, new_ballx, new_bally, new_ballz; sscanf(server_reply,"(%f,%f,%f,%f,%f) \\n", &new_enemyx, &new_enemyy, &new_ballx, &new_bally, &new_ballz); update_enemy_coord(new_enemyx, new_enemyy); update_ball_coord(new_ballx, new_bally, new_ballz); } } close(sockfd); return 0; } void client_init() { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { puts("FAILEDDDDDDDDDDDDDDDDDD"); printf("Could not create socket \\n"); } puts("Socket created \\n"); memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(GAME_PORT); if (inet_pton(AF_INET, ip, &serv_addr.sin_addr.s_addr) != 1) { puts("FAILEDDDDDDDDDDDDDDDDDD"); die2("inet_pton: %s \\n", ip); return; } else { printf("Connected to Server @ %s\\n", ip); } pthread_create(&worker,(void*) 0, client_thread, 0); } void logic_update(float dt) { int ball_dir = -1; enemy_x = -player_x; enemy_y = -player_y; ball_x = 0; ball_y = 0; ball_z += ball_dir * dt * 3; if (ball_z < -5) { ball_dir = 1; } if (ball_z > 0) { ball_dir = -1; } }
1
#include <pthread.h> pthread_mutex_t a; pthread_mutex_t b; int k; int j; void* fn1(void * args){ pthread_mutex_lock(&a);; pthread_mutex_unlock(&b);; } void* fn2(void * args){ pthread_mutex_lock(&b);; pthread_mutex_unlock(&a);; } int main(int argc, const char *argv[]) { pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, &fn1, 0); pthread_create(&thread2, 0, &fn2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; }
0
#include <pthread.h> struct propset { char *str; int row; int delay; int dir; }; int setup(int nstrings, char *strings[], struct propset props[]); pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; int main(int ac, char *av[]) { int c; pthread_t thrds[10]; struct propset props[10]; void *animate(); int num_msg ; int i; if ( ac == 1 ){ printf("usage: tanimate string ..\\n"); exit(1); } num_msg = setup(ac-1,av+1,props); for(i=0 ; i<num_msg; i++) if ( pthread_create(&thrds[i], 0, animate, &props[i])){ fprintf(stderr,"error creating thread"); endwin(); exit(0); } while(1) { c = getch(); if ( c == 'Q' ) break; if ( c == ' ' ) for(i=0;i<num_msg;i++) props[i].dir = -props[i].dir; if ( c >= '0' && c <= '9' ){ i = c - '0'; if ( i < num_msg ) props[i].dir = -props[i].dir; } } pthread_mutex_lock(&mx); for (i=0; i<num_msg; i++ ) pthread_cancel(thrds[i]); endwin(); return 0; } int setup(int nstrings, char *strings[], struct propset props[]) { int num_msg = ( nstrings > 10 ? 10 : nstrings ); int i; srand(getpid()); for(i=0 ; i<num_msg; i++){ props[i].str = strings[i]; props[i].row = i; props[i].delay = 1+(rand()%15); props[i].dir = ((rand()%2)?1:-1); } initscr(); crmode(); noecho(); clear(); mvprintw(LINES-1,0,"'Q' to quit, '0'..'%d' to bounce",num_msg-1); return num_msg; } void *animate(void *arg) { struct propset *info = arg; int len = strlen(info->str)+2; int col = rand()%(COLS-len-3); while( 1 ) { usleep(info->delay*20000); pthread_mutex_lock(&mx); move( info->row, col ); addch(' '); addstr( info->str ); addch(' '); move(LINES-1,COLS-1); refresh(); pthread_mutex_unlock(&mx); col += info->dir; if ( col <= 0 && info->dir == -1 ) info->dir = 1; else if ( col+len >= COLS && info->dir == 1 ) info->dir = -1; } }
1
#include <pthread.h> int source[2]; int out_channel[2]; int in_channel[2]; int th_id = 0; pthread_mutex_t mid; pthread_mutex_t ms[2]; void *robot (void * arg) { int id = -1; pthread_mutex_lock (&mid); id = th_id; th_id++; pthread_mutex_unlock (&mid); __VERIFIER_assert (id >= 0); __VERIFIER_assert (id < 2); int size = source[id]; int dir = 0; int position = 0; int duration = 0; int battery = 0; while (1) { printf ("t: id %d dir %d pos %d dur %d bat %d\\n", id, dir, position, duration, battery); if (battery == 0) { pthread_mutex_lock (&ms[id]); battery = out_channel[id]; pthread_mutex_unlock (&ms[id]); if (battery == 0) break; } if (duration == 0) { duration = __VERIFIER_nondet_int(1, 50); dir = __VERIFIER_nondet_int (0, 1); if (dir == 0) dir = -1; } duration--; battery--; position += dir; if (position >= size) position = 0; if (position < 0) position = size - 1; } return 0; } int main () { int i, k, tid; pthread_t ths[2]; __libc_init_poet (); for (i = 0; i < 2; i++) { source[i] = __VERIFIER_nondet_int (0, 20); printf ("m: source[%d] = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } printf ("==============\\n"); pthread_mutex_init (&mid, 0); i = 0; out_channel[i] = 10; pthread_mutex_init (&ms[i], 0); pthread_create (&ths[i], 0, robot, 0); i++; out_channel[i] = 10; pthread_mutex_init (&ms[i], 0); pthread_create (&ths[i], 0, robot, 0); i++; __VERIFIER_assert (i == 2); k = 0; while (k < 2) { tid = __VERIFIER_nondet_int (0, 2 - 1); if (out_channel[tid] != 0) { printf ("m: picking tid %d out[tid] %d\\n", tid, out_channel[tid]); pthread_mutex_lock (&ms[tid]); out_channel[tid] = __VERIFIER_nondet_int (0, 10); printf ("m: charging tid %d out[tid] %d\\n", tid, out_channel[tid]); if (out_channel[tid] == 0) { k++; } pthread_mutex_unlock (&ms[tid]); } } i = 0; pthread_join (ths[i], 0); i++; pthread_join (ths[i], 0); i++; __VERIFIER_assert (i == 2); return 0; }
0
#include <pthread.h> long nNumber = 0; pthread_mutex_t mutx; void * minus(void* arg); void * plus(void* arg); void console_setting_for_eclipse_debugging(void) { setvbuf(stdout,0, _IONBF,0); setvbuf(stderr,0, _IONBF,0); } void * minus(void* arg) { int i; for(i= 0; i<100000; i++) { pthread_mutex_lock(&mutx); nNumber--; printf("[THREAD1]%ld, %d\\n",nNumber, i); pthread_mutex_unlock(&mutx); } return 0; } void * plus(void* arg) { int i; for(i= 0; i<100000; i++) { pthread_mutex_lock(&mutx); nNumber++; printf("[THREAD2]%ld, %d\\n",nNumber, i); pthread_mutex_unlock(&mutx); } return 0; } int main() { pthread_t thread; pthread_t thread2; int *status, *status2; pthread_mutex_init(&mutx,0); pthread_create(&thread, 0, minus, 0); pthread_create(&thread2, 0, plus, 0); pthread_join(thread, (void**)&status); pthread_join(thread2, (void**)&status2); printf("%ld",nNumber); pthread_mutex_destroy(&mutx); return 0; }
1
#include <pthread.h> void main_memory(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); } pthread_mutex_lock(&mux_iord_result); if (!mux_iord_buffer.isUpdated) while(pthread_cond_wait(&mux_iord_execution_wait, &mux_iord_result) != 0); pthread_mutex_unlock(&mux_iord_result); if ((separa_MemRead & cs.value) == ativa_MemRead) mem_data = memoria[mux_iord_buffer.value/4].value; if ((cs.value & separa_MemWrite) == ativa_MemWrite){ memoria[mux_iord_buffer.value/4].value = b_value; memoria[mux_iord_buffer.value/4].isUpdated = 1; } pthread_barrier_wait(&current_cycle); pthread_barrier_wait(&update_registers); } }
0
#include <pthread.h> struct producers { int buffer[4]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty, notfull; }; void init(struct producers * b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct producers * b, int data) { while(1){ pthread_mutex_lock(&b->lock); if((b->writepos +1) % 4 == b->readpos){ pthread_mutex_unlock(&b->lock); }else{ break; } } b->buffer[b->writepos] = data; b->writepos ++; if(4 <= b->writepos) b->writepos = 0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct producers * b) { int data; pthread_mutex_lock(&b->lock); while(b->writepos == b->readpos) pthread_cond_wait(&b->notempty, &b->lock); data = b->buffer[b->readpos]; b->readpos++; if(b->readpos >= 4) b->readpos = 0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct producers buffer; void * producer(void * data) { int n; for(n=0;n<10;n++) { printf("Producer: %d-->\\n", n); put(&buffer, n); } put(&buffer, (-1)); return 0; } void * consumer(void * data) { int d; while(1) { d = get(&buffer); if((-1) == d) break; printf("Consumer: --> %d\\n", d); } return 0; } int main(void) { pthread_t tha, thb; void * retval; init(&buffer); pthread_create(&tha, 0, producer, 0); pthread_create(&thb, 0, consumer, 0); pthread_join(tha, &retval); pthread_join(thb, &retval); return 0; }
1
#include <pthread.h> struct msg { struct msg* m_next; }; struct msg* workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void process_msg(void) { struct msg* mp; while (1) { pthread_mutex_lock(&qlock); while (workq == 0) pthread_cond_wait(&qready, &qlock); mp = workq; workq = mp->m_next; pthread_mutex_unlock(&qlock); } } void enqueue_msg(struct msg* mp) { pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); }
0
#include <pthread.h> int max_darts; int darts_in_circle; pthread_mutex_t * darts_in_circle_lock; int total_darts_currently_thrown; pthread_mutex_t * total_darts_currently_thrown_lock; pthread_mutex_t * rand_lock; int done; int dart_is_multiple; pthread_mutex_t * dart_is_multiple_lock; pthread_cond_t * dart_is_multiple_cond_var; void *simulate_darts () { double x, y, dist; while (!done) { pthread_mutex_lock(rand_lock); x = (double) rand() / (double) 32767; y = (double) rand() / (double) 32767; pthread_mutex_unlock(rand_lock); dist = sqrt(pow(x - 0.5, 2) + pow(y - 0.5, 2)); if (dist <= 0.5) { pthread_mutex_lock(darts_in_circle_lock); darts_in_circle++; pthread_mutex_unlock(darts_in_circle_lock); } pthread_mutex_lock(total_darts_currently_thrown_lock); total_darts_currently_thrown++; if (total_darts_currently_thrown % 1000000 == 0) { pthread_mutex_lock (dart_is_multiple_lock); dart_is_multiple = 1; pthread_mutex_unlock (dart_is_multiple_lock); pthread_cond_broadcast (dart_is_multiple_cond_var); } pthread_mutex_unlock(total_darts_currently_thrown_lock); if (total_darts_currently_thrown >= max_darts) { pthread_mutex_lock (dart_is_multiple_lock); dart_is_multiple = 1; pthread_mutex_unlock (dart_is_multiple_lock); pthread_cond_broadcast (dart_is_multiple_cond_var); done = 1; } } pthread_exit (0); } void *print_pi() { while (!done) { pthread_mutex_lock(dart_is_multiple_lock); while (!dart_is_multiple) { pthread_cond_wait (dart_is_multiple_cond_var, dart_is_multiple_lock); } pthread_mutex_lock(darts_in_circle_lock); pthread_mutex_lock(total_darts_currently_thrown_lock); double result = 4.0 * darts_in_circle / total_darts_currently_thrown; pthread_mutex_unlock(darts_in_circle_lock); pthread_mutex_unlock(total_darts_currently_thrown_lock); printf("PI: %f\\n",result); printf("\\n"); dart_is_multiple = 0; pthread_mutex_unlock(dart_is_multiple_lock); } pthread_exit (0); } int main(int argc, char *argv[]) { int i; srand ((unsigned) time(0)); rand_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init(rand_lock, 0); darts_in_circle_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init(darts_in_circle_lock, 0); total_darts_currently_thrown_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init(total_darts_currently_thrown_lock, 0); dart_is_multiple_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init(dart_is_multiple_lock, 0); dart_is_multiple_cond_var = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (dart_is_multiple_cond_var, 0); done = 0; dart_is_multiple = 0; darts_in_circle = 0; total_darts_currently_thrown = 0; int number_of_threads; sscanf (argv[1], "%d", &number_of_threads); sscanf (argv[2], "%d", &max_darts); pthread_t * print_thread = (pthread_t *) malloc (sizeof(pthread_t *)); pthread_create (print_thread, 0, print_pi, 0); pthread_t **sim_thread = (pthread_t **) malloc (sizeof(pthread_t *) * number_of_threads); for (i = 0; i < number_of_threads; i++) { sim_thread[i] = (pthread_t *) malloc (sizeof(pthread_t *)); if (pthread_create (sim_thread[i], 0, simulate_darts, 0)) { fprintf (stderr, "Error creating consumer thread %d.\\n", i); exit(-1); } } for (i = 0; i < number_of_threads; i++) { if (pthread_join (*sim_thread[i], 0)) { fprintf (stderr, "Error joining sim thread with id %d\\n", i); exit(-1); } } if (pthread_join (*print_thread, 0)) { fprintf (stderr, "Error joining with print_thread"); exit(-1); } }
1
#include <pthread.h> int nC = 0; pthread_cond_t c_dormir; pthread_cond_t c_corte; pthread_mutex_t m_activo; pthread_mutex_t m_corte; pthread_mutex_t m_nC; void *Barbero(void *arg); void *Cliente(void *arg); void cortaPelo(); void abandona(); void despierta(); void recibirCorte(); void duerme(); int main(){ pthread_t barbero, cliente1, cliente2,cliente3, cliente4,cliente5, cliente6,cliente7, cliente8,cliente9, cliente10; pthread_mutex_init(&m_activo, 0); pthread_mutex_init(&m_corte, 0); pthread_mutex_init(&m_nC, 0); pthread_cond_init(&c_dormir, 0); pthread_cond_init(&c_corte, 0); pthread_create(&barbero, 0, Barbero, 0); pthread_create(&cliente1, 0, Cliente, 0); sleep(1); pthread_create(&cliente2, 0, Cliente, 0); sleep(1); pthread_create(&cliente3, 0, Cliente, 0); sleep(1); pthread_create(&cliente4, 0, Cliente, 0); sleep(10); pthread_create(&cliente5, 0, Cliente, 0); sleep(1); pthread_create(&cliente6, 0, Cliente, 0); sleep(1); pthread_create(&cliente7, 0, Cliente, 0); sleep(1); pthread_create(&cliente8, 0, Cliente, 0); sleep(1); pthread_create(&cliente9, 0, Cliente, 0); sleep(1); pthread_create(&cliente10, 0, Cliente, 0); pthread_join(barbero, 0); pthread_join(cliente1, 0); pthread_join(cliente2, 0); pthread_join(cliente3, 0); pthread_join(cliente4, 0); pthread_join(cliente5, 0); pthread_join(cliente6, 0); pthread_join(cliente7, 0); pthread_join(cliente8, 0); pthread_join(cliente9, 0); pthread_join(cliente10, 0); pthread_cond_destroy(&c_dormir); pthread_cond_destroy(&c_corte); pthread_mutex_destroy(&m_activo); pthread_mutex_destroy(&m_corte); pthread_mutex_destroy(&m_nC); exit(0); } void *Barbero(void *arg){ while(1){ pthread_mutex_lock(&m_nC); if(nC == 0) { pthread_mutex_unlock(&m_nC); duerme(); } else{ pthread_mutex_unlock(&m_nC); cortaPelo(); } } } void *Cliente(void *arg){ pthread_mutex_lock(&m_nC); if(nC == 3) { pthread_mutex_unlock(&m_nC); abandona(); } else { if(nC == 0){ nC++; pthread_mutex_unlock(&m_nC); despierta(); } else { nC++; pthread_mutex_unlock(&m_nC); recibirCorte(); } pthread_mutex_lock(&m_nC); nC--; pthread_mutex_unlock(&m_nC); } } void cortaPelo(){ sleep(2); pthread_cond_signal(&c_corte); } void abandona(){ printf("Cliente: adios, esto esta lleno\\n"); } void despierta(){ printf("/ cliente grita desesperado por que le atiendan / \\n"); pthread_cond_signal(&c_dormir); recibirCorte(); } void recibirCorte(){ printf("Cliente: buenas tardes, vengo a cortarme el pelo\\n"); pthread_mutex_lock(&m_corte); pthread_cond_wait(&c_corte, &m_corte); pthread_mutex_unlock(&m_corte); printf("Cliente: gracias por el corte\\n"); } void duerme(){ printf("Barbero: A dormir estoy molido\\n"); pthread_mutex_lock(&m_activo); pthread_cond_wait(&c_dormir, &m_activo); pthread_mutex_unlock(&m_activo); printf("Barbero: Quien me haya despertado se quedará sin patillas\\n"); }
0
#include <pthread.h> void mux_4_alusrcb(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_ALUSrcB0 | separa_ALUSrcB1) & cs.value) >> ALUSrcB0_POS) & 0x03) == 0) mux_alusrcb_buffer.value = b_value; else if(((((separa_ALUSrcB0 | separa_ALUSrcB1) & cs.value) >> ALUSrcB0_POS) & 0x03) == 1) mux_alusrcb_buffer.value = 4; else if(((((separa_ALUSrcB0 | separa_ALUSrcB1) & cs.value) >> ALUSrcB0_POS) & 0x03) == 2) { pthread_mutex_lock(&sign_extend_mutex); if (!se.isUpdated) while(pthread_cond_wait(&sign_extend_cond,&sign_extend_mutex) != 0); pthread_mutex_unlock(&sign_extend_mutex); mux_alusrcb_buffer.value = se.value; } else { pthread_mutex_lock(&shift_left_mutex); if (!shift_left.isUpdated) while(pthread_cond_wait(&shift_left_cond, &shift_left_mutex) != 0); pthread_mutex_unlock(&shift_left_mutex); mux_alusrcb_buffer.value = shift_left.value; } pthread_mutex_lock(&mux_alusrcb_result); mux_alusrcb_buffer.isUpdated = 1; pthread_cond_signal(&mux_alusrcb_execution_wait); pthread_mutex_unlock(&mux_alusrcb_result); pthread_barrier_wait(&current_cycle); mux_alusrcb_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> void *print_odd(void *data); void *print_even(void *data); int counter = 1; pthread_mutex_t mutex_counter; pthread_cond_t cond_odd, cond_even; void main() { pthread_mutex_init(&mutex_counter, 0); pthread_cond_init(&cond_odd, 0); pthread_cond_init(&cond_even, 0); pthread_t thread_odd, thread_even; pthread_create(&thread_odd, 0, print_odd, 0); pthread_create(&thread_even, 0, print_even, 0); pthread_join(thread_odd, 0); pthread_join(thread_even, 0); pthread_mutex_destroy(&mutex_counter); pthread_cond_destroy(&cond_odd); pthread_cond_destroy(&cond_even); pthread_exit(0); } void *print_odd(void *data) { while (counter < 100) { pthread_mutex_lock(&mutex_counter); while (counter % 2 == 0) { pthread_cond_wait(&cond_odd, &mutex_counter); } printf("%d\\n", counter++); pthread_mutex_unlock(&mutex_counter); pthread_cond_signal(&cond_even); } } void *print_even(void *data) { while (counter < 100) { pthread_mutex_lock(&mutex_counter); while (counter % 2 != 0) { pthread_cond_wait(&cond_even, &mutex_counter); } printf("%d\\n", counter++); pthread_mutex_unlock(&mutex_counter); pthread_cond_signal(&cond_odd); } }
0
#include <pthread.h> static char *map; static int nr_bits; extern FILE *logfile; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void bm_alloc(int bits) { int bytes = bits / 8; if (!bits || bits < 0 || bits % 8) DIE("invalid bit count: %d", bits); map = malloc(bytes); if (!map) DIE_PERROR("allocating bitmap failed"); memset(map, 0, bytes); nr_bits = bits; DEBUG("alloc map @ %p for %d bits\\n", map, nr_bits); } void bm_destroy(void) { free(map); } static void access_ok(int bit) { if (bit > nr_bits) DIE("bitmap overflow"); } void bm_set(int bit_nr) { int byte = bit_nr / 8; int bit = bit_nr % 8; access_ok(bit_nr); pthread_mutex_lock(&mutex); *(map + byte) |= 1 << bit; pthread_mutex_unlock(&mutex); } void bm_clear(int bit_nr) { int byte = bit_nr / 8; int bit = bit_nr % 8; access_ok(bit_nr); pthread_mutex_lock(&mutex); *(map + byte) &= ~(1 << bit); pthread_mutex_unlock(&mutex); } int bm_test(int bit_nr) { int byte = bit_nr / 8; int bit = bit_nr % 8; int set; access_ok(bit_nr); pthread_mutex_lock(&mutex); set = *(map + byte) & (1 << bit); pthread_mutex_unlock(&mutex); if (set) return 1; else return 0; } void bm_dump(void) { int i; printf("bitmap:\\n"); for (i = 0; i < nr_bits; i++) { if (bm_test(i)) printf("+"); else printf("-"); } printf("\\n"); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void thread1(void *arg) { pthread_cleanup_push((void *) pthread_mutex_unlock,(void *)&mutex ); while(1) { printf( "thread1 is running \\n" ); pthread_mutex_lock( &mutex ); pthread_cond_wait( &cond,&mutex ); printf( "thread1 applied the condition\\n" ); pthread_mutex_unlock( &mutex ); sleep(4); } pthread_cleanup_pop(0); } void *thread2( void *arg ) { while(1) { printf( "thread2 is running \\n" ); pthread_mutex_lock( &mutex ); pthread_cond_wait( &cond,&mutex ); printf( "thread2 applied the condition\\n" ); pthread_mutex_unlock( &mutex ); sleep(1); } } int main() { pthread_t tid1,tid2; printf( "condition variable study!\\n" ); pthread_mutex_init( &mutex,0 ); pthread_cond_init( &cond,0 ); pthread_create( &tid1,0,(void *)thread1,0 ); pthread_create( &tid2,0,(void *)thread2,0 ); do { pthread_cond_signal( &cond ); }while(1); sleep(50); pthread_exit(0); }
0
#include <pthread.h> int typ; int pocz; int kon; int numer; } par_t; volatile int running_threads = 0; volatile int p_count = 0; pthread_mutex_t primes_mutex = PTHREAD_MUTEX_INITIALIZER; int pid; int chid; void *count_primes2(void *arg) { int status; int coid; par_t reply; coid = ConnectAttach(ND_LOCAL_NODE, pid, chid, _NTO_SIDE_CHANNEL, 0); while (1) { par_t args; args.typ = 10; args.numer = pthread_self(); status = MsgSend(coid, &args, sizeof(args), &reply, sizeof(reply)); if (reply.typ == 1) { sleep(1); int primes_count = 0; printf("Proces: %d, watek: %d\\n", getpid(), pthread_self()); int i; for (i = reply.pocz; i < reply.kon; i++) { int c; int prime = 1; for (c = 2; c <= i / 2; c++) { if (i % c == 0) { prime = 0; break; } } if (prime && i != 0 && i != 1) primes_count++; } printf("\\twatek: %d, poczatek %d, koniec %d, primes %d\\n", pthread_self(), reply.pocz, reply.kon, primes_count); pthread_mutex_lock(&primes_mutex); p_count += primes_count; pthread_mutex_unlock(&primes_mutex); } else if (reply.typ == 0) { return 0; } } } int main(int argc, char *argv[]) { pid = getpid(); chid = ChannelCreate(0); if (argc != 4) { printf("Proper usage: ./lab2 range_start range_end thread_count\\n"); return 0; } int range_start = atoi(argv[1]); int range_end = atoi(argv[2]); int threads_count = atoi(argv[3]); int range_length = (range_end - range_start) / (threads_count * 4); int i = 0; int f = 0; pthread_t tid; while (1) { if (running_threads < threads_count && !f) { pthread_create(&tid, 0, count_primes2, 0); running_threads++; printf("in if\\n"); } else { printf("in first else\\n"); f = 1; par_t args; int rcvid = MsgReceive(chid, &args, sizeof(args), 0); if (range_start + (i + 1) * range_length <= range_end) { printf("if <=range end\\n"); if (args.typ == 10) { args.typ = 1; args.numer = i; args.pocz = range_start + i * range_length; args.kon = range_start + (i + 1) * range_length; int status = MsgReply(rcvid, EOK, &args, sizeof(args)); if (-1 == status) { perror("MsgReply"); } } i++; } else { printf(".else args.typ == 0 "); args.typ = 0; int status = MsgReply(rcvid, EOK, &args, sizeof(args)); if (-1 == status) { perror("MsgReply"); } printf("Watek %d poprosil, ale nie ma\\n", args.numer); running_threads--; if (!running_threads) { break; } } } } printf("Liczb pierwszych: %d\\n", p_count); return 0; }
1
#include <pthread.h> struct INSTANCE_CACHE { const char *module; const char *instance; }; static pthread_mutex_t icMutex = PTHREAD_MUTEX_INITIALIZER; static struct INSTANCE_CACHE *ic = 0; static int icSize = 0; static const char * add_ic(const char *module, const char *instance) { struct INSTANCE_CACHE *new; const char *ret; char *buf; new = (struct INSTANCE_CACHE *)realloc(ic, (icSize + 1)*sizeof(struct INSTANCE_CACHE)); if (new == 0) { return 0; } new[icSize].module = strdup(module); if (instance == 0) ret = new[icSize].module; else { if (asprintf(&buf, "%s%s", module, instance) == -1) { free(new); return 0; } ret = buf; } new[icSize].instance = ret; ic = new; icSize++; return ret; } static const char * find_ic(const char *module) { int i; for (i = 0; i < icSize; i++) if (strcmp(ic[i].module, module) == 0) break; if (i == icSize) return 0; return ic[i].instance; } const char * genomInstanceName(const char *moduleName) { const char *instance, *genomInstance, *ret;; char *envvar; pthread_mutex_lock(&icMutex); genomInstance = find_ic(moduleName); if (genomInstance != 0) { ret = genomInstance; goto done; } if (asprintf(&envvar, "GENOM_INSTANCE_%s", moduleName) == -1) { ret = 0; goto done; } instance = getenv(envvar); free(envvar); ret = add_ic(moduleName, instance); done: pthread_mutex_unlock(&icMutex); return ret; } const char * genomInstanceSuffixName(const char *moduleName, const char *suffix) { char *result; char *instance; char *envvar; if (asprintf(&envvar, "GENOM_INSTANCE_%s", moduleName) == -1) goto oom; instance = getenv(envvar); free(envvar); if (instance == 0) { if (asprintf(&result, "%s%s", moduleName, suffix) == -1) goto oom; } else { if (asprintf(&result,"%s%s%s", moduleName, instance, suffix) == -1) goto oom; } return result; oom: fprintf(stderr, "genomInstanceSuffixName: out of memory\\n"); return 0; }
0
#include <pthread.h> static pthread_t thread_timer; static pthread_mutex_t mutex; void qos_enter_critical(void){ pthread_mutex_lock( &mutex ); } void qos_exit_critical(void){ pthread_mutex_unlock( &mutex ); } static void ctrl_break_handler( int ctrl ){ int res; res = pthread_cancel( thread_timer ); if( res != 0 ){ printf( "pthread_cancel failed\\n" ); exit( 1 ); } res = pthread_join( thread_timer, 0 ); if( res != 0 ){ printf( "pthread_join failed\\n" ); exit( 1 ); } pthread_mutex_destroy( &mutex ); if( ctrl == SIGTSTP ){ exit( 0 ); } else if (ctrl==SIGINT){ exit( 0 ); } return; } static void *thread_timer_callback( void *parg ){ int res; res = pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, 0 ); if( res != 0 ){ printf( "Thread pthread_setcancelstate failed\\n" ); exit( 1 ); } res = pthread_setcanceltype( PTHREAD_CANCEL_DEFERRED, 0 ); if( res != 0 ){ printf( "Thread pthread_setcanceltype failed\\n" ); exit( 1 ); } for(;;){ struct timespec timeout = { 0, 0 }; timeout.tv_sec = ( (1000 * 1000 * 1000) / OS_TICKS_PER_SEC ) / (1000 * 1000 * 1000); timeout.tv_nsec = ( (1000 * 1000 * 1000) / OS_TICKS_PER_SEC ) % (1000 * 1000 * 1000); qos_tick(); nanosleep( &timeout, 0 ); } pthread_exit( 0 ); return 0; } bool qos_port_init(void){ int res = 0; signal( SIGINT, ctrl_break_handler ); signal( SIGTSTP, ctrl_break_handler); printf( "usuage: ctrl-c exit\\n" ); res = pthread_mutex_init( &mutex, 0 ); if( res != 0 ){ printf( "mutex initialization failed\\n" ); exit( 1 ); return 0; } res = pthread_create( &thread_timer, 0, (void *)thread_timer_callback, 0 ); if( res != 0 ){ printf( "create thread error\\n" ); exit( 1 ); return 0; } return 1; } void qos_verify_process( char const * const express, char const * const file_name, int line ){ printf( "verify FAIL:%s file:%s @%d\\n", express, file_name, line ); }
1
#include <pthread.h> int status = -1; pthread_mutex_t infrared_mutex; extern int send_data(const char *data,const unsigned int length); int infrared_init() { pinMode (infrared_Pin, INPUT); pthread_mutex_init(&infrared_mutex,0); return 1; } void reset_status() { pthread_mutex_lock(&infrared_mutex); status = -1; pthread_mutex_unlock(&infrared_mutex); return; } void *infrared_run(void *arg) { char buf[3] = {0}; int read_data; buf[0] = 'I'; buf[2] = '\\0'; while(1) { read_data = digitalRead(infrared_Pin); if( read_data == status ) { sleep(1); continue; } if( read_data ) { bee_stop(); buf[1] = '0'; } else { bee_start(); buf[1] = '1'; } send_data(buf, strlen(buf)); pthread_mutex_lock(&infrared_mutex); status = read_data; pthread_mutex_unlock(&infrared_mutex); sleep(1); } pthread_exit(0); }
0