text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct product_cons { int buffer[5]; pthread_mutex_t lock; int readpos,writepos; pthread_cond_t notempty; pthread_cond_t notfull; }buffer; void init(struct product_cons *p) { pthread_mutex_init(&p->lock,0); pthread_cond_init(&p->notempty,0); pthread_cond_init(&p->notfull,0); p->readpos = 0; p->readpos = 0; } void finish(struct product_cons *p) { pthread_mutex_destroy(&p->lock); pthread_cond_destroy(&p->notempty); pthread_cond_destroy(&p->notfull); p->readpos = 0; p->writepos = 0; } void put(struct product_cons *p,int data) { pthread_mutex_lock(&p->lock); if((p->writepos+1)%5 == p->readpos) { printf("producer wait for not full\\n"); pthread_cond_wait(&p->notfull,&p->lock); } p->buffer[p->writepos] =data; p->writepos++; if(p->writepos>=5) { p->writepos = 0; } pthread_cond_signal(&p->notempty); pthread_mutex_unlock(&p->lock); } int get(struct product_cons *p) { int data; pthread_mutex_lock(&p->lock); if(p->readpos == p->writepos) { printf("comsumer wait for not empty\\n"); pthread_cond_wait(&p->notempty,&p->lock); } data = p->buffer[p->readpos]; p->readpos++; pthread_cond_signal(&p->notfull); pthread_mutex_unlock(&p->lock); return data; } void *producer(void *data) { int n; for(n=1;n<=50;++n) { sleep(1); printf("put the %d product \\n",n); put(&buffer,n); printf("put the %d product sucess\\n",n); } printf("producer stopped\\n"); return 0; } void *consumer(void *data) { static int cnt =0; int num; while(1) { sleep(2); printf("get product \\n"); num = get(&buffer); printf("get the %d product sucess\\n",num); if(++cnt == 30) { break; } } printf("consumer stopped\\n"); return 0; } int main(int argc ,char *argv[]) { pthread_t th_a,th_b; void *retval; init(&buffer); pthread_create(&th_a,0,producer,0); pthread_create(&th_b,0,consumer,0); pthread_join(th_a,&retval); pthread_join(th_b,&retval); finish(&buffer); return 0; }
1
#include <pthread.h> int is_prime[1000000]; int TCOUNT=0, COUNT_LIMIT=0; int count = 0, latest_prime = 2; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void set_up_primetable () { int i, j; for (i=0; i<1000000; i++) is_prime[i] = 1; is_prime[0] = is_prime[1] = 0; for (i=2; i<1000; i++) { if (is_prime[i]==1) { for (j=2; j<=1000000/i; j++) is_prime[i*j] = 0; } } } void *prime_count (void *t) { int i, j; double result = 0.0; long my_id = (long) t; while (count < TCOUNT) { pthread_mutex_lock(&count_mutex); if (is_prime[count]==1) latest_prime = count; count++; if (count==COUNT_LIMIT) { printf("prime_count(): thread %ld, p = %d, prime reached.\\n", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } else { printf("prime_count(): thread %ld, p = %d.\\n", my_id, count); if (is_prime[count]==1) printf("prime_count(): thread %ld, find prime = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); sleep(1); if (count==COUNT_LIMIT) 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<COUNT_LIMIT) { printf("watch_count(): thread %ld, p = %d. Going into wait...\\n", my_id, count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. p = %d.\\n", my_id, count); count += latest_prime; printf("watch_count(): thread %ld Updating the value of p...\\n", my_id); printf("the latest prime found before p = %d.\\n", latest_prime); printf("watch_count(): thread %ld Count p now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char **argv) { if (argc!=3) { printf("usage: ./a.out <tcount> <count_limit>\\n"); exit(-1); } int i, rc; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; TCOUNT = atoi(argv[1]); COUNT_LIMIT = atoi(argv[2]); set_up_primetable(); pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *) t1); pthread_create(&threads[1], &attr, prime_count, (void *) t2); pthread_create(&threads[2], &attr, prime_count, (void *) t3); for (i=0; i<3; i++) pthread_join(threads[i], 0); printf("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); return 0; }
0
#include <pthread.h> { int *arr, *ret, l, r; pthread_mutex_t *mutex; } ds_pthread; void pthread_diff(void *ps) { int idx_i, local = 0; ds_pthread *p = (ds_pthread *) ps; for(idx_i = p->l + 1; idx_i <= p->r; idx_i++) local += (p->arr)[idx_i] - (p->arr)[idx_i - 1]; pthread_mutex_lock(p->mutex); *(p -> ret) += local; pthread_mutex_unlock(p->mutex); } void merge(int *arr, int size, int l, int m, int r) { int *temp = (int *) malloc(sizeof(int) * size); if(temp == 0) { fprintf(stderr, "Malloc error.\\n"); exit(1); } int i, j, k; for(i = l, j = m + 1, k = l; i <= m && j <= r;) { if(arr[i] < arr[j]) temp[k++] = arr[i++]; else temp[k++] = arr[j++]; } while(i <= m) temp[k++] = arr[i++]; while(j <= r) temp[k++] = arr[j++]; for(i = l; i <= r; i++) arr[i] = temp[i]; free(temp); } inline void SWAP(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } void quickSort(int *arr, int lbnd, int rbnd) { if(lbnd >= rbnd) return; int pivot, pidx, i; pivot = arr[rbnd]; for(pidx = lbnd, i = lbnd; pidx < rbnd && i < rbnd; i++) { if(arr[i] <= pivot) { SWAP(&arr[pidx], &arr[i]); pidx++; } } SWAP(&arr[pidx], &arr[rbnd]); quickSort(arr, lbnd, pidx - 1); quickSort(arr, pidx + 1, rbnd); } void pthread_sort(void *ps) { ds_pthread *p = (ds_pthread *) ps; quickSort(p -> arr, p -> l, p -> r); } int *initialize(int seed, int size) { int idx_i; srand(seed); int *ret = (int *) malloc(sizeof(int) * size); if(ret == 0) { fprintf(stderr, "Malloc failed.\\n"); exit(1); } for(idx_i = 0; idx_i < size; idx_i++) ret[idx_i] = rand(); return ret; } int main(int argc, char **argv) { if(argc != 3) { fprintf(stderr, "Too few or too many arguments.\\n"); return 0; } int seed = atoi(argv[1]); int size = atoi(argv[2]); if(seed < 0 || size <= 0) { fprintf(stderr, "Invalid arguments.\\n"); return 0; } int *arr = initialize(seed, size); int idx_i, ret = 0; pthread_t pid[2]; pthread_mutex_t mutex; pthread_mutex_init(&mutex, 0); ds_pthread ps[2] = {{arr, &ret, 0, size / 2, &mutex}, {arr, &ret, size / 2 + 1, size - 1, &mutex}}; for(idx_i = 0; idx_i < 2; idx_i++) pthread_create(&pid[idx_i], 0, (void *)pthread_sort, &ps[idx_i]); for(idx_i = 0; idx_i < 2; idx_i++) pthread_join(pid[idx_i], 0); merge(arr, size, 0, size / 2, size - 1); ps[1].l --; for(idx_i = 0; idx_i < 2; idx_i++) pthread_create(&pid[idx_i], 0, (void *)pthread_diff, &ps[idx_i]); for(idx_i = 0; idx_i < 2; idx_i++) pthread_join(pid[idx_i], 0); printf("Total difference: %d\\n", ret); free(arr); return 0; }
1
#include <pthread.h> struct thread_data { int t_index; }; int global_count = 0; pthread_t thread_id[10]; pthread_mutex_t cnt_mutex; pthread_cond_t cnt_cond; void *thread_start_A(void *param) { struct thread_data *t_param = (struct thread_data *) param; int tid = (*t_param).t_index; int sleep_time; sleep_time = (rand() % 2) + 1; sleep(sleep_time); pthread_mutex_lock(&cnt_mutex); global_count++; printf("Thread A (id %ld) finished incrementing\\n", thread_id[tid]); if(global_count == 10 -1 ) pthread_cond_signal(&cnt_cond); pthread_mutex_unlock(&cnt_mutex); pthread_exit(0); } void *thread_start_B(void *param) { pthread_t *tid = (pthread_t *) param; pthread_mutex_lock(&cnt_mutex); while (global_count != 10 - 1) pthread_cond_wait(&cnt_cond, &cnt_mutex); printf("Thread B (id %ld): global count = %d \\n", *tid, global_count); pthread_mutex_unlock(&cnt_mutex); pthread_exit(0); } int main() { int no_of_threads, i; struct thread_data param[10]; pthread_t tid; pthread_mutex_init(&cnt_mutex, 0); pthread_cond_init(&cnt_cond, 0); pthread_create(&tid, 0, thread_start_B, (void *) &tid); for(i=0; i<10 -1; i++) { param[i].t_index = i; pthread_create(&thread_id[i], 0, thread_start_A, (void *) &param[i]); } for(i=0; i<10 -1; i++) { pthread_join(thread_id[i], 0); } pthread_join(tid, 0); printf("All threads terminated\\n"); pthread_mutex_destroy(&cnt_mutex); pthread_cond_destroy(&cnt_cond); }
0
#include <pthread.h> pthread_cond_t vacio, lleno; pthread_mutex_t lock; int array[10]; int n_elementos=0; void * productor(); void * consumidor(); int main(int argc, char ** argv){ srand(time(0)); int i; pthread_mutex_init(&lock, 0); pthread_cond_init(&vacio, 0); pthread_cond_init(&lleno, 0); pthread_t pid[2]; for(i=0;i<10;i++){ array[i] = rand()%5; n_elementos++; } pthread_create(&pid[0], 0, (void *) productor, 0); pthread_create(&pid[1], 0, (void *) consumidor, 0); pthread_join(pid[0], 0); pthread_join(pid[1], 0); pthread_exit(0); } void * productor(){ int i, j; pthread_mutex_lock(&lock); for(j=0;j<10;j++){ i = rand() % 5; while(n_elementos==10){ printf("Vector lleno\\n"); pthread_cond_wait(&lleno, &lock); } array[j]=i; n_elementos++; printf("PNum elementos es %d\\n", n_elementos); printf("Producto creado\\n"); } pthread_mutex_unlock(&lock); pthread_cond_signal(&vacio); pthread_exit(0); } void * consumidor(){ int i, j; int dato; pthread_mutex_lock(&lock); for(j=0;j<10; j++){ i = rand() % 5; while(n_elementos==0){ printf("Vector vacio\\n"); pthread_cond_wait(&vacio, &lock); } dato=array[j]; n_elementos--; printf("CNum elementos es %d\\n", n_elementos); printf("Producto consumido %d\\n", dato); } pthread_mutex_unlock(&lock); pthread_cond_signal(&lleno); pthread_exit(0); }
1
#include <pthread.h> struct account{ int balance; int credits; int debits; pthread_mutex_t lock; }; struct account accounts[10]; void * transactions(void * args){ int i,v; int a1,a2; for(i=0;i<100;i++){ v = (int) random() % 100; a1 = (int) random() % 10; while((a2 = (int) random() % 10) == a1); if(a1 < a2){ pthread_mutex_lock(&accounts[a1].lock); pthread_mutex_lock(&accounts[a2].lock); }else{ pthread_mutex_lock(&accounts[a2].lock); pthread_mutex_lock(&accounts[a1].lock); } accounts[a1].balance += v; accounts[a1].credits += v; accounts[a2].balance -= v; accounts[a2].debits += v; if(a1 < a2){ pthread_mutex_unlock(&accounts[a2].lock); pthread_mutex_unlock(&accounts[a1].lock); }else{ pthread_mutex_unlock(&accounts[a1].lock); pthread_mutex_unlock(&accounts[a2].lock); } } return 0; } int main(int argc, char * argv[]){ int n_threads,i; pthread_t * threads; if(argc < 2){ fprintf(stderr, "ERROR: Require number of threads\\n"); exit(1); } n_threads = atol(argv[1]); if(n_threads <= 0){ fprintf(stderr, "ERROR: Invalivd value for number of threads\\n"); exit(1); } threads = calloc(n_threads, sizeof(pthread_t)); for(i=0;i<10;i++){ accounts[i].balance=1000; accounts[i].credits=0; accounts[i].debits=0; pthread_mutex_init(&accounts[i].lock, 0); } for(i=0;i<n_threads;i++){ pthread_create(&threads[i], 0, transactions, 0); } for(i=0;i<n_threads;i++){ pthread_join(threads[i], 0); } for(i=0;i<10;i++){ printf("ACCOUNT %d: %d (%d)\\n", i, accounts[i].balance, 1000 +accounts[i].credits-accounts[i].debits); } free(threads); for(i=0;i<10;i++){ pthread_mutex_destroy(&accounts[i].lock); } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t people_garden = PTHREAD_COND_INITIALIZER; long int size = 0; void update_garden() { int i, random1, random2; for (i = 0; i < 100; i++) { pthread_mutex_lock(&mutex); if (size == 1000) { pthread_cond_wait(&people_garden, &mutex); } random1 = (rand() % 30); size += random1; pthread_mutex_unlock(&mutex); random2 = (rand() % 20); if (size && size > random2) { pthread_mutex_lock(&mutex); size -= random2; pthread_cond_signal(&people_garden); pthread_mutex_unlock(&mutex); } printf("People in Garden %li...\\n", size); } } void* east(void *arg) { printf("East entrance opened...\\n"); update_garden(); pthread_exit(0); } void* west(void *arg) { printf("West entrance opened...\\n"); update_garden(); pthread_exit(0); } int main(int argc, char* argv[]) { time_t t; pthread_t west_thread; pthread_t east_thread; srand((unsigned) time(&t)); pthread_create(&west_thread, 0, west, 0); pthread_create(&east_thread, 0, east, 0); pthread_join(west_thread, 0); pthread_join(east_thread, 0); printf("Garden closed\\n"); if (size) { pthread_mutex_lock(&mutex); size -= size; pthread_cond_signal(&people_garden); pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> int MAX_CUPCAKES = 10; int total_cupcakes = 5; pthread_mutex_t cupcake_lock = PTHREAD_MUTEX_INITIALIZER; void *bakery(); void *producer(); void *consumer(); bool check = 1; int main() { pthread_t bakery_thread; pthread_create(&bakery_thread, 0, bakery, 0); pthread_join(bakery_thread, 0); return 0; } void *bakery() { pthread_t consumer_thread, producer_thread; pthread_create(&producer_thread, 0, producer, 0); pthread_create(&consumer_thread, 0, consumer, 0); pthread_join(producer_thread, 0); pthread_join(consumer_thread, 0); printf("Bakery is out of cupcakes.\\n"); return 0; } void *producer() { while(check) { while(total_cupcakes == MAX_CUPCAKES); pthread_mutex_lock(&cupcake_lock); total_cupcakes++; printf("Cupcake produced, total cupcakes is: %d, next cupcake produced in 2 seconds.\\n", total_cupcakes); pthread_mutex_unlock(&cupcake_lock); sleep(2); } return 0; } void *consumer() { while(check) { while(total_cupcakes == 0); pthread_mutex_lock(&cupcake_lock); total_cupcakes--; printf("Cupcake consumed, total cupcakes is: %d, next cupcakes consumed in 1 second.\\n", total_cupcakes); pthread_mutex_unlock(&cupcake_lock); sleep(1); } return 0; }
0
#include <pthread.h> static struct rimage *wait_for_image(struct wthread *wt) { return get_rimg_by_name(wt->snapshot_id, wt->path); } uint64_t forward_image(struct rimage *rimg) { uint64_t ret; int fd = proxy_to_cache_fd; pthread_mutex_lock(&(rimg->in_use)); pr_info("Forwarding %s:%s (%lu bytes)\\n", rimg->path, rimg->snapshot_id, rimg->size); if (write_remote_header( fd, rimg->snapshot_id, rimg->path, O_APPEND, rimg->size) < 0) { pr_perror("Error writing header for %s:%s", rimg->path, rimg->snapshot_id); pthread_mutex_unlock(&(rimg->in_use)); return -1; } ret = send_image(fd, rimg, O_APPEND, 0); if (ret < 0) { pr_perror("Unable to send %s:%s to image cache", rimg->path, rimg->snapshot_id); pthread_mutex_unlock(&(rimg->in_use)); return -1; } else if (ret != rimg->size) { pr_perror("Unable to send %s:%s to image proxy (sent %lu bytes, expected %lu bytes", rimg->path, rimg->snapshot_id, ret, rimg->size); pthread_mutex_unlock(&(rimg->in_use)); return -1; } pr_info("Finished forwarding %s:%s (sent %lu bytes)\\n", rimg->path, rimg->snapshot_id, rimg->size); pthread_mutex_unlock(&(rimg->in_use)); return ret; } int image_proxy(bool background, char *local_proxy_path, char *fwd_host, unsigned short fwd_port) { pthread_t local_req_thr; pr_info("CRIU to Proxy Path: %s, Cache Address %s:%hu\\n", local_proxy_path, fwd_host, fwd_port); local_req_fd = setup_UNIX_server_socket(local_proxy_path); if (local_req_fd < 0) { pr_perror("Unable to open CRIU to proxy UNIX socket"); return -1; } if (opts.ps_socket != -1) { proxy_to_cache_fd = opts.ps_socket; pr_info("Re-using ps socket %d\\n", proxy_to_cache_fd); } else { proxy_to_cache_fd = setup_TCP_client_socket(fwd_host, fwd_port); if (proxy_to_cache_fd < 0) { pr_perror("Unable to open proxy to cache TCP socket"); return -1; } } if (init_daemon(background, wait_for_image)) return -1; if (pthread_create( &local_req_thr, 0, accept_local_image_connections, (void *) &local_req_fd)) { pr_perror("Unable to create local requests thread"); return -1; } pthread_join(local_req_thr, 0); join_workers(); pr_info("Finished image proxy."); return 0; }
1
#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; }
0
#include <pthread.h> struct data { int tid; char buffer[100]; } tdata1, tdata2; pthread_mutex_t lock1; pthread_mutex_t lock2; pthread_cond_t cond1; pthread_cond_t cond2; int mySharedCounter = 0; int go1 = 0; int go2 = 0; void helper(void *tdata, pthread_mutex_t *l1, pthread_cond_t *c1, int *goP1, pthread_mutex_t *l2, pthread_cond_t *c2, int *goP2) { struct data *d = (struct data*) tdata; pthread_mutex_lock(l1); while (!(*goP1)) { printf("thread %d sleeps until condition %lu - goP1 is set\\n", d->tid, (long)goP1); pthread_cond_wait(c1, l1); } printf("helper func reached by thread %d : after waiting for c1 and l1\\n", d->tid); sleep(1); pthread_mutex_lock(l2); while (!(*goP2)) { printf("thread %d sleeps until condition %lu - goP2 is set \\n", d->tid, (long)goP2); pthread_cond_wait(c2, l2); } printf("helper func reached by thread %d : after waiting for c2 and l2\\n", d->tid); sleep(1); mySharedCounter++; printf("thread %d performed its critical region and exiting ..\\n", d->tid); pthread_mutex_unlock(l2); pthread_mutex_unlock(l1); pthread_exit(0); } void *worker1(void *tdata) { struct data *d = (struct data*) tdata; printf("thread %d says %s\\n", d->tid, d->buffer); helper(d, &lock1, &cond1, &go1, &lock2, &cond2, &go2); pthread_exit(0); } void *worker2(void *tdata) { struct data *d = (struct data*) tdata; printf("thread %d says %s\\n", d->tid, d->buffer); helper(d, &lock1, &cond1, &go1, &lock2, &cond2, &go2); pthread_exit(0); } int main(char *argc[], int argv) { int failed; pthread_t thread1, thread2; void *status1, *status2; pthread_mutex_init(&lock1, 0); pthread_mutex_init(&lock2, 0); printf(" ************** MAIN THREAD: CREATING THREADS ! ***************\\n"); tdata1.tid = 1; strcpy(tdata1.buffer, "hello"); failed = pthread_create(&thread1, 0, worker1, (void*)&tdata1); if (failed) { printf("thread_create failed!\\n"); return -1; } tdata2.tid = 2; strcpy(tdata2.buffer, "world"); failed = pthread_create(&thread2, 0, worker2, (void*)&tdata2); if (failed) { printf("thread_create failed!\\n"); return -1; } printf("Main thread finished creating threads and is now sleeping\\n"); sleep(1); printf("Main thread woke up!\\n"); pthread_mutex_lock(&lock1); go1 = 1; pthread_cond_broadcast(&cond1); pthread_mutex_unlock(&lock1); pthread_mutex_lock(&lock2); go2 = 1; pthread_cond_broadcast(&cond2); pthread_mutex_unlock(&lock2); pthread_join(thread1, &status1); pthread_join(thread2, &status2); printf("If you see this message, we were lucky!\\n"); printf("mySharedCounter = %d\\n", mySharedCounter); pthread_exit(0); }
1
#include <pthread.h> int bufer[10], contador[10]; sem_t full[3], empty; pthread_mutex_t ex_buf = PTHREAD_MUTEX_INITIALIZER, ex_cont = PTHREAD_MUTEX_INITIALIZER; int main (void) { int i; extern sem_t full[3], empty; extern int contador[10]; pthread_t consumidor[3], productor; int v[3]; void *Productor (void *), *Consumidor (void *); pthread_attr_t atributos; pthread_attr_init (&atributos); sem_init (&empty, 0, 10); for (i = 0; i < 10; i++) contador[i] = 0; for (i = 0; i < 3; i++) sem_init (&full[i], 0, 0); srandom (-time (0)); pthread_create (&productor, &atributos, Productor, 0); for (i = 0; i < 3; i++) { v[i] = i; pthread_create (&consumidor[i], &atributos, Consumidor, &v[i]); } pthread_join (productor, 0); for (i = 0; i < 3; i++) pthread_join (consumidor[i], 0); } void * Productor (void *p) { int p_index = 0, item, i, j, suma = 0; extern sem_t full[3], empty; extern pthread_mutex_t ex_buf; extern int bufer[10]; for (i = 0; i < 100; i++) { suma += (item = random () % 100); sem_wait (&empty); pthread_mutex_lock (&ex_buf); bufer[p_index] = item; pthread_mutex_unlock (&ex_buf); for (j = 0; j < 3; j++) sem_post (&full[j]); p_index = (p_index + 1) % 10; fprintf (stdout, "Pro: Item %d\\n", item); } fprintf (stdout, "Pro: Suma %d\\n", suma); } void * Consumidor (void *p) { int c_index = 0, item, i, *index, suma = 0; extern sem_t full[3], empty; extern pthread_mutex_t ex_buf, ex_cont; extern int bufer[10], contador[10]; index = (int *) p; for (i = 0; i < 100; i++) { sem_wait (&full[*index]); pthread_mutex_lock (&ex_buf); item = bufer[c_index]; pthread_mutex_unlock (&ex_buf); pthread_mutex_lock (&ex_cont); if (++contador[c_index] == 3) { contador[c_index] = 0; sem_post (&empty); } pthread_mutex_unlock (&ex_cont); c_index = (c_index + 1) % 10; suma += item; fprintf (stdout, "C%2d: Item %d\\n", *index, item); } fprintf (stdout, "C%2d: Suma %d\\n", *index, suma); }
0
#include <pthread.h> PENSANDO, HAMBRIENTO, COMIENDO } status; status estado[5]; sem_t mutex, s[5]; pthread_cond_t no_comida; pthread_mutex_t cmutex; int comida = 0; void Pensar(int); void Comer(int); void CogerTenedores(int); void SoltarTenedores(int); void Comprobar(int); void *Cocinero(void *); int main() { extern status estado[5]; extern sem_t mutex, s[5]; pthread_t filosofo[5], cocinero; int i, v[5], value; void *Filosofo(void *); pthread_cond_init(&no_comida, 0); pthread_mutex_init(&cmutex, 0); sem_init(&mutex, 0, 1); for (i = 0; i < 5; i++) sem_init(&s[i], 0, 0); for (i = 0; i < 5; i++) estado[i] = PENSANDO; if (value = pthread_create(&cocinero, 0, Cocinero, (void *) 0)) exit(value); for (i = 0; i < 5; i++) { v[i] = i; if (value = pthread_create(&filosofo[i], 0, Filosofo, (void *) &v[i])) exit(value); } for (i = 0; i < 5; i++) pthread_join(filosofo[i], 0); } void *Filosofo(void *id) { int indice, i; indice = *(int *) id; for (i = 0; i < 10; i++) { Pensar(indice); CogerTenedores(indice); Comer(indice); SoltarTenedores(indice); } } void CogerTenedores(int i) { extern sem_t s[5], mutex; extern status estado[5]; sem_wait(&mutex); estado[i] = HAMBRIENTO; Comprobar(i); sem_post(&mutex); sem_wait(&s[i]); } void SoltarTenedores(int i) { extern sem_t mutex; extern status estado[5]; sem_wait(&mutex); estado[i] = PENSANDO; Comprobar(((i) !=0 ? (i)-1 : (5 -1))); Comprobar((((i)+1)%5)); sem_post(&mutex); } void Comprobar(int i) { extern sem_t s[5]; extern status estado[5]; if (estado[i] == HAMBRIENTO && estado[((i) !=0 ? (i)-1 : (5 -1))] != COMIENDO && estado[(((i)+1)%5)] != COMIENDO) { estado[i] = COMIENDO; sem_post(&s[i]); } } void Comer(int i) { int s, c; extern int comida; extern pthread_mutex_t cmutex; extern pthread_cond_t no_comida; c = random() % 5; for (;;) { pthread_mutex_lock (&cmutex); if (comida > c) { comida -= c; printf ("Filosofo %d comera %d unidades de %d\\n", i, c, comida+c); pthread_mutex_unlock(&cmutex); break; } printf ("Filosofo %d se bloquea en espera de comida\\n", i); pthread_cond_wait (&no_comida, &cmutex); pthread_mutex_unlock(&cmutex); } s = random() % 10; printf("Filosofo %d comiendo %d segundos\\n", i, s); sleep(s); } void Pensar(int i) { int s; s = random() % 10; printf("Filosofo %d pensando %d segundos\\n", i, s); sleep(s); } void *Cocinero(void *p) { extern int comida; extern pthread_mutex_t cmutex; int c; for (;;) { c = random() % 10; pthread_mutex_lock(&cmutex); comida += c; printf ("Preparada comida: %d\\n", c); pthread_cond_broadcast (&no_comida); pthread_mutex_unlock(&cmutex); sleep(10); } }
1
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; int i = 0; void * fn1(void *arg) { pthread_t tid = pthread_self(); printf("thread1 %lu\\n", tid); while (1) { sleep(1); printf("loop in thread1\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("thread1 after cond wait: %d\\n", i); pthread_mutex_unlock(&mutex); } } void * fn2(void *arg) { pthread_t tid = pthread_self(); printf("thread2 %lu\\n", tid); while (1) { i++; sleep(1); if (i % 5 == 0) { pthread_cond_signal(&cond); } printf("loop in thread2\\n"); } } void * fn3(void *arg) { pthread_t tid = pthread_self(); printf("thread3 %lu\\n", tid); while (1) { sleep(1); printf("loop in thread3\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("thread3 after cond wait: %d\\n", i); pthread_mutex_unlock(&mutex); } } int main(int argc, char *argv[]) { pthread_t tid1, tid2, tid3; pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); pthread_create(&tid1, 0, fn1, 0); pthread_create(&tid2, 0, fn2, 0); pthread_create(&tid3, 0, fn3, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_join(tid3, 0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void initialize_flag() { pthread_mutex_init(&thread_flag_mutex, 0); pthread_cond_init(&thread_flag_cv, 0); thread_flag = 0; } void do_work() { printf("hello\\n"); } void* thread_function(void* thread_arg) { while (1) { pthread_mutex_lock(&thread_flag_mutex); while (!thread_flag) { pthread_cond_wait(&thread_flag_cv, &thread_flag_mutex); } pthread_mutex_unlock(&thread_flag_mutex); do_work(); } return 0; } 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); } int main(int argc, char** argv) { const int ciExitSuccess = 0; pthread_t thread; int inVal = 0; pthread_create(&thread, 0, &thread_function, 0); while (1) { printf("Enter any non zero number! "); scanf("%d", &inVal); set_thread_flag(inVal); } return ciExitSuccess; }
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)); }
0
#include <pthread.h> union mynum { long long longlong; double flonum; }; int nthreads; int pleasequit=0; long long maxiterations=0; pthread_barrier_t barrier; pthread_mutex_t maxiter_mutex=PTHREAD_MUTEX_INITIALIZER; void * calculate(void *param) { double localpi=0.0; long long threadno=((union mynum *)param)->longlong; long long i=threadno; long long tocheck; pthread_mutex_lock(&maxiter_mutex); do { tocheck=i+1000000*nthreads; if (tocheck>maxiterations && !pleasequit) maxiterations=tocheck; else if (tocheck>maxiterations && pleasequit) break; pthread_mutex_unlock(&maxiter_mutex); for (; i< tocheck ; i+=nthreads) { localpi += 1.0/(i*4.0 + 1.0); localpi -= 1.0/(i*4.0 + 3.0); } fprintf(stderr, "Thread %lld working, %lld iterations passed\\n", threadno, i-threadno); pthread_barrier_wait(&barrier); pthread_mutex_lock(&maxiter_mutex); } while(!pleasequit); pthread_mutex_unlock(&maxiter_mutex); fprintf(stderr, "Thread %lld finished, %lld iterations, partial sum %.16f\\n", threadno, i-threadno, localpi); ((union mynum *)param)->flonum=localpi; return param; } void handlesigint2(int sig) { fputs("Wait, I'm quitting right now...\\n", stderr); signal(sig, handlesigint2); } int main(int argc, char** argv) { double pi = 0; int i; pthread_t * ids; union mynum * params; sigset_t set; int sig; sigemptyset(&set); sigaddset(&set, SIGINT); sigprocmask(SIG_BLOCK, &set, 0); if (argc >= 1) nthreads=atol(argv[1]); if (nthreads < 1) { fprintf(stderr, "usage: %s threadnum\\n", argv[0]); exit(0); } pthread_barrier_init(&barrier, 0, nthreads); params=malloc(nthreads*sizeof(union mynum)); ids=malloc(nthreads*sizeof(pthread_t)); for(i=0; i< nthreads; i++) { params[i].longlong=i; pthread_create(ids+i, 0, calculate, (void*)(params+i)); } do { if (sigwait(&set, &sig)<0) { perror("Waiting for signal"); exit(0); } } while(sig!=SIGINT); fprintf(stderr, "Sigint caught\\n"); pleasequit=1; signal(SIGINT, handlesigint2); sigprocmask(SIG_UNBLOCK, &set, 0); for(i=0; i<nthreads; i++) { union mynum * res; pthread_join(ids[i], (void **)&res); pi+=res->flonum; } pi *= 4.0; printf ("pi = %.16f\\n", pi); return (0); }
1
#include <pthread.h> { float alpha1; float alpha2; float beta0; float beta1; float beta2; } parameters; parameters fastFilter; pthread_mutex_t paramMutex; void* fastFilterThread(void*); void* slowFilterThread(void*); int main( void ) { pthread_t fastFilterThreadID; pthread_t slowFilterThreadID; fastFilter.alpha1 = -1.691; fastFilter.alpha2 = 0.7327; fastFilter.beta0 = 0.0104; fastFilter.beta1 = 0.0209; fastFilter.beta2 = 0.0104; pthread_mutex_init(&paramMutex, 0); pthread_create(&fastFilterThreadID, 0, fastFilterThread, 0); pthread_create(&slowFilterThreadID, 0, slowFilterThread, 0); pthread_join(fastFilterThreadID, 0); pthread_join(slowFilterThreadID, 0); exit(0); } void* fastFilterThread(void* unUsed){ float x, x1, x2; float y, y1, y2; FILE *fpRead, *fpWrite; fpRead = fopen("Data1.txt", "r"); fpWrite = fopen("Output.txt", "w"); while(fscanf(fpRead, "%f", &x) != EOF){ pthread_mutex_lock(&paramMutex); y = fastFilter.beta0*x + fastFilter.beta1*x1 + fastFilter.beta2*x2 - fastFilter.alpha1*y1 - fastFilter.alpha2*y2; pthread_mutex_unlock(&paramMutex); fprintf(fpWrite, "%f\\n", y); x2 = x1; x1 = x; y2 = y1; y1 = y; usleep(50000); } fclose(fpRead); fclose(fpWrite); pthread_exit(0); return(0); } void* slowFilterThread(void* unUsed){ parameters slowFilter = {-1.561, 0.6414, 0.0201, 0.0402, 0.0201}; float x, x1, x2; float y, y1, y2; FILE *fpRead; fpRead = fopen("Data2.txt", "r"); while(fscanf(fpRead, "%f", &x) != EOF){ y = slowFilter.beta0*x + slowFilter.beta1*x1 + slowFilter.beta2*x2 - slowFilter.alpha1*y1 - slowFilter.alpha2*y2; if (y>2 && y1<2){ pthread_mutex_lock(&paramMutex); fastFilter.alpha1 = -1.4755; fastFilter.alpha2 = 0.5869; fastFilter.beta0 = 0.7656; fastFilter.beta1 = -1.5312; fastFilter.beta2 = 0.7656; pthread_mutex_unlock(&paramMutex); }else if(y<2 && y1>2){ pthread_mutex_lock(&paramMutex); fastFilter.alpha1 = -1.691; fastFilter.alpha2 = 0.7327; fastFilter.beta0 = 0.0104; fastFilter.beta1 = 0.0209; fastFilter.beta2 = 0.0104; pthread_mutex_unlock(&paramMutex); } x2 = x1; x1 = x; y2 = y1; y1 = y; usleep(200000); } fclose(fpRead); pthread_exit(0); return(0); }
0
#include <pthread.h> pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER; int IMAGE[10]; int QuelThreadTravail[10]; struct data { int i; }data; void * Travail(void *par){ sleep(rand()%5); struct data *mon_D1 = (struct data*)par; pthread_t moi=pthread_self(); if(mon_D1->i==1){ printf("Je suis %i le premier thread %i\\n",mon_D1->i,(int)moi); sleep(rand()%4); for(int i=0; i<10;i++){ pthread_mutex_lock(&verrou); IMAGE[i]=5; QuelThreadTravail[i]=1; printf("Le thread %i travail sur la zone Z%i de l'image\\n",QuelThreadTravail[i],i); pthread_mutex_unlock(&verrou); sleep(1); } } else{ printf("Je suis %i le deuxième thread %i\\n", mon_D1->i,(int)moi); for(int i=0;i<10;i++){ pthread_mutex_lock(&verrou); while(QuelThreadTravail[i]!=1){ pthread_mutex_unlock(&verrou); pthread_mutex_lock(&verrou); } IMAGE[i]=IMAGE[i]+3; QuelThreadTravail[i]++; printf("Le thread %i travail sur la zone Z%i de l'image\\n",QuelThreadTravail[i],i); pthread_mutex_unlock(&verrou); } printf("Je suis le thread %i j'ai fini en %i-er\\n",(int)moi,mon_D1->i); } pthread_exit(0); } int main(){ srand(time(0)); pthread_t T1; pthread_t T2; struct data *D1; for(int i=0;i<10;i++){ IMAGE[i]=0; QuelThreadTravail[i]=0; } D1 = malloc(sizeof(data)); (*D1).i=1; pthread_create(&T1,0,Travail,D1); D1 = malloc(sizeof(data)); (*D1).i=2; pthread_create(&T2,0,Travail,D1); pthread_join(T1,0); pthread_join(T2,0); return 0; }
1
#include <pthread.h> int kbhit(void) { struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if(ch != EOF) { ungetc(ch, stdin); return 1; } return 0; } int getkey(void) { while(1) { if(kbhit()) { int key = getchar(); return key; } } } pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; char stuff[6] = "*****"; int check_stuff() { for(int i=0;i<5;++i) { if(stuff[i] != '*') { return 0; } } return 1; } void set_stuff() { for(int i=0;i<5;++i) { } } void reset_stuff() { for(int i=0;i<5;++i) { stuff[i] = '*'; } } struct data { pthread_t th; int id; }; void * thread(void * arg) { struct data * parameters = (struct data *)arg; char character = 'A' + parameters->id; int shift = 1 + parameters->id; while(1) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); if(check_stuff()) printf("[%c] got the condition signal (success) !\\n", character); else printf("[%c] got the condition signal (failure) !\\n", character), pthread_mutex_unlock(&mutex); } return 0; } int main() { struct data tab[5]; for(int i=0; i<5; ++i) { tab[i].id = i; pthread_create(&tab[i].th, 0, thread, &tab[i]); } while(1) { pthread_mutex_lock(&mutex); switch(getkey()) { case 'S': case 's': set_stuff(); pthread_cond_signal(&cond); break; case 'B': case 'b': set_stuff(); pthread_cond_broadcast(&cond); break; } pthread_mutex_unlock(&mutex); reset_stuff(); } sleep(10); pthread_exit(0); exit(0); }
0
#include <pthread.h> pthread_mutex_t buffer_mutex; int fill = 0; char buffer[100][50]; char *fetch(char *link) { int fd = open(link, O_RDONLY); if (fd < 0) { fprintf(stderr, "failed to open file: %s", link); return 0; } int size = lseek(fd, 0, 2); assert(size >= 0); char *buf = Malloc(size+1); buf[size] = '\\0'; assert(buf); lseek(fd, 0, 0); char *pos = buf; while(pos < buf+size) { int rv = read(fd, pos, buf+size-pos); assert(rv > 0); pos += rv; } close(fd); return buf; } void edge(char *from, char *to) { if(!from || !to) return; char temp[50]; temp[0] = '\\0'; char *fromPage = parseURL(from); char *toPage = parseURL(to); strcpy(temp, fromPage); strcat(temp, "->"); strcat(temp, toPage); strcat(temp, "\\n"); pthread_mutex_lock(&buffer_mutex); strcpy(buffer[fill++], temp); pthread_mutex_unlock(&buffer_mutex); } int main(int argc, char *argv[]) { pthread_mutex_init(&buffer_mutex, 0); int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/simple_loop/pagea", 5, 4, 15, fetch, edge); assert(rc == 0); return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/simple_loop.out"); }
1
#include <pthread.h> struct async_waitlist { int counter; struct sigevent sigev; struct waitlist list[0]; }; int getaddrinfo_a (int mode, struct gaicb *list[], int ent, struct sigevent *sig) { struct sigevent defsigev; struct requestlist *requests[ent]; int cnt; volatile int total = 0; int result = 0; if (mode != GAI_WAIT && mode != GAI_NOWAIT) { __set_errno (EINVAL); return EAI_SYSTEM; } if (sig == 0) { defsigev.sigev_notify = SIGEV_NONE; sig = &defsigev; } pthread_mutex_lock (&__gai_requests_mutex); for (cnt = 0; cnt < ent; ++cnt) if (list[cnt] != 0) { requests[cnt] = __gai_enqueue_request (list[cnt]); if (requests[cnt] != 0) ++total; else result = EAI_SYSTEM; } else requests[cnt] = 0; if (total == 0) { pthread_mutex_unlock (&__gai_requests_mutex); if (mode == GAI_NOWAIT) __gai_notify_only (sig, sig->sigev_notify == SIGEV_SIGNAL ? getpid () : 0); return result; } else if (mode == GAI_WAIT) { pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct waitlist waitlist[ent]; int oldstate; total = 0; for (cnt = 0; cnt < ent; ++cnt) if (requests[cnt] != 0) { waitlist[cnt].cond = &cond; waitlist[cnt].next = requests[cnt]->waiting; waitlist[cnt].counterp = &total; waitlist[cnt].sigevp = 0; waitlist[cnt].caller_pid = 0; requests[cnt]->waiting = &waitlist[cnt]; ++total; } pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &oldstate); while (total > 0) pthread_cond_wait (&cond, &__gai_requests_mutex); pthread_setcancelstate (oldstate, 0); if (pthread_cond_destroy (&cond) != 0) abort (); } else { struct async_waitlist *waitlist; waitlist = (struct async_waitlist *) malloc (sizeof (struct async_waitlist) + (ent * sizeof (struct waitlist))); if (waitlist == 0) result = EAI_AGAIN; else { pid_t caller_pid = sig->sigev_notify == SIGEV_SIGNAL ? getpid () : 0; total = 0; for (cnt = 0; cnt < ent; ++cnt) if (requests[cnt] != 0) { waitlist->list[cnt].cond = 0; waitlist->list[cnt].next = requests[cnt]->waiting; waitlist->list[cnt].counterp = &waitlist->counter; waitlist->list[cnt].sigevp = &waitlist->sigev; waitlist->list[cnt].caller_pid = caller_pid; requests[cnt]->waiting = &waitlist->list[cnt]; ++total; } waitlist->counter = total; waitlist->sigev = *sig; } } pthread_mutex_unlock (&__gai_requests_mutex); return result; }
0
#include <pthread.h> int msglevel = LOG_INFO; FILE *log_file = 0; void pmesg(int level, const char *source, long int line_number, const char *format, ...) { va_list args; char log_type[10]; int new_msglevel = msglevel % 10; if (level > new_msglevel) return; switch (level) { case LOG_ERROR: sprintf(log_type, "ERROR"); break; case LOG_INFO: sprintf(log_type, "INFO"); break; case LOG_WARNING: sprintf(log_type, "WARNING"); break; case LOG_DEBUG: sprintf(log_type, "DEBUG"); break; default: sprintf(log_type, "UNKNOWN"); break; } if (msglevel > 10) { time_t t1 = time(0); char *s = ctime(&t1); s[strlen(s) - 1] = 0; fprintf(log_file ? log_file : stderr, "[%s][%s][%s][%ld]\\t", s, log_type, source, line_number); } else { fprintf(log_file ? log_file : stderr, "[%s][%s][%ld]\\t", log_type, source, line_number); } __builtin_va_start((args)); vfprintf(log_file ? log_file : stderr, format, args); ; fflush(log_file ? log_file : stderr); } void pmesg_safe(pthread_mutex_t * flag, int level, const char *source, long int line_number, const char *format, ...) { va_list args; char log_type[10]; int new_msglevel = msglevel % 10; if (level > new_msglevel) return; switch (level) { case LOG_ERROR: sprintf(log_type, "ERROR"); break; case LOG_INFO: sprintf(log_type, "INFO"); break; case LOG_WARNING: sprintf(log_type, "WARNING"); break; case LOG_DEBUG: sprintf(log_type, "DEBUG"); break; default: sprintf(log_type, "UNKNOWN"); break; } if (flag) pthread_mutex_lock(flag); if (msglevel > 10) { time_t t1 = time(0); char *s = ctime(&t1); s[strlen(s) - 1] = 0; fprintf(log_file ? log_file : stderr, "[%s][%s][%s][%ld]\\t", s, log_type, source, line_number); } else { fprintf(log_file ? log_file : stderr, "[%s][%s][%ld]\\t", log_type, source, line_number); } __builtin_va_start((args)); vfprintf(log_file ? log_file : stderr, format, args); ; fflush(log_file ? log_file : stderr); if (flag) pthread_mutex_unlock(flag); } int get_debug_level() { return msglevel % 10; } void set_debug_level(int level) { msglevel = level; } void set_log_file(FILE * file) { log_file = file; }
1
#include <pthread.h> struct cl_listener *cl_listener_alloc() { struct cl_listener *p = smalloc( sizeof(struct cl_listener), cl_listener_free); cl_listener_init(p); return p; } void cl_listener_init(struct cl_listener *p) { INIT_LIST_HEAD(&p->head); p->delegate = 0; p->lock = 0; } void cl_listener_clear(struct cl_listener *p) { if(p->lock) { pthread_mutex_lock(p->lock); if( ! list_singular(&p->head)) { list_del_init(&p->head); } pthread_mutex_unlock(p->lock); p->lock = 0; } } void cl_listener_free(struct cl_listener *p) { cl_listener_clear(p); sfree(p); }
0
#include <pthread.h> struct data { long counter[256]; }; const int SIZE = sizeof(struct data); static pthread_mutex_t output_mutex; static struct data data; void *run(void *raw_name) { time_t thread_start = time(0); char *name = (char *) raw_name; int fd = -1; time_t open_start = time(0); while (fd == -1) { fd = open(raw_name, O_RDONLY); if (fd < 0 && errno == EMFILE) { sleep(1); continue; } if (fd < 0) { char msg[256]; sprintf(msg, "error while opening file=%s", name); handle_error(fd, msg, THREAD_EXIT); } } time_t open_duration = time(0) - open_start; time_t total_mutex_wait = 0; char buffer[16384]; struct data local_data; long *scounter = local_data.counter; while (TRUE) { ssize_t size_read = read(fd, buffer, 16384); if (size_read == 0) { break; } if (size_read < 0) { char msg[256]; sprintf(msg, "error while reading file=%s", name); handle_error(size_read, msg, THREAD_EXIT); } int i; for (i = 0; i < size_read; i++) { unsigned char c = buffer[i]; scounter[c]++; } } close(fd); time_t thread_duration = time(0) - thread_start; unsigned int i; long *tcounter = data.counter; pthread_mutex_lock(&output_mutex); printf("------------------------------------------------------------\\n"); printf("%s: pid=%ld\\n", name, (long) getpid()); printf("open duration: ~ %ld sec; total wait for data: ~ %ld sec; thread duration: ~ %ld\\n", (long) open_duration, (long) total_mutex_wait, (long) thread_duration); printf("------------------------------------------------------------\\n"); for (i = 0; i < 256; i++) { tcounter[i] += scounter[i]; long val = tcounter[i]; if (! (i & 007)) { printf("\\n"); } if ((i & 0177) < 32 || i == 127) { printf("\\\\%03o: %10ld ", i, val); } else { printf("%4c: %10ld ", (char) i, val); } } printf("\\n\\n"); printf("------------------------------------------------------------\\n\\n"); fflush(stdout); pthread_mutex_unlock(&output_mutex); return 0; } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage\\n\\n"); printf("%s file1 file2 file3 ... filen\\ncount files, show accumulated output after having completed one file\\n\\n", argv[0]); exit(1); } time_t start_time = time(0); int retcode = 0; int i; printf("%d files will be read\\n", argc-1); fflush(stdout); for (i = 0; i < 256; i++) { data.counter[i] = 0L; } retcode = pthread_mutex_init(&output_mutex, 0); handle_error(retcode, "creating mutex", PROCESS_EXIT); pthread_t *threads = malloc((argc-1)*sizeof(pthread_t)); for (i = 1; i < argc; i++) { retcode = pthread_create(&(threads[i-1]), 0, run, argv[i]); handle_error(retcode, "starting thread", PROCESS_EXIT); } pthread_mutex_lock(&output_mutex); printf("%d threads started\\n", argc-1); fflush(stdout); pthread_mutex_unlock(&output_mutex); for (i = 0; i < argc-1; i++) { retcode = pthread_join(threads[i], 0); handle_error(retcode, "joining thread", PROCESS_EXIT); } retcode = pthread_mutex_destroy(&output_mutex); handle_error(retcode, "destroying mutex", PROCESS_EXIT); time_t total_time = time(0) - start_time; printf("total %ld sec\\n", (long) total_time); printf("done\\n"); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex[5]; void* philosopher(void* arg) { int *number; number=(int*) arg; while(1) { int result=0; sleep(1); printf("philosopher %d is thinking\\n",*number ); sleep(1); pthread_mutex_lock(&mutex[*number]); result=pthread_mutex_trylock(&mutex[(*number+1)%5]); if(result!=0) { pthread_mutex_unlock(&mutex[(*number+1)%5]); sleep(2); pthread_mutex_lock(&mutex[(*number+1)%5]); printf("philosopher %d is eating\\n",*number ); sleep(2); pthread_mutex_unlock(&mutex[*number]); pthread_mutex_unlock(&mutex[(*number+1)%5]); continue; } printf("philosopher %d is eating\\n",*number ); sleep(2); pthread_mutex_unlock(&mutex[*number]); pthread_mutex_unlock(&mutex[(*number+1)%5]); } } int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutexattr_t *attr); int pthread_mutex_destroy(pthread_mutex_t *mutex); int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg); int pthread_join(pthread_t thread,void **rval_ptr); int main(int argc, char const *argv[]) { pthread_mutex_t mutex; pthread_mutex_init(&mutex,0); pthread_t tid1,tid2,tid3,tid4,tid5; int test1 = 0; int *attr1 = &test1; int test2 = 1; int *attr2 = &test2; int test3 = 2; int *attr3 = &test3; int test4 = 3; int *attr4 = &test4; int test5 = 4; int *attr5 = &test5; pthread_create(&tid1,0,(void*)philosopher,(void*)attr1); pthread_create(&tid2,0,(void*)philosopher,(void*)attr2); pthread_create(&tid3,0,(void*)philosopher,(void*)attr3); pthread_create(&tid4,0,(void*)philosopher,(void*)attr4); pthread_create(&tid5,0,(void*)philosopher,(void*)attr5); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); pthread_join(tid5,0); return 0; }
0
#include <pthread.h> double* A; double* B; double produto_escalar = 0; int id; } TArgs; pthread_mutex_t s; void* trabalhador(void* args){ TArgs* arg = (TArgs*) args; int id = arg->id; int inicio, fim, i; double soma; inicio = id*(6/2); fim = inicio + (6/2); if(id == 2 -1 && fim < 6) fim = 6; printf("Thread[%d]: %d a %d\\n", id, inicio, fim); for(i=inicio, soma=0; i<fim; i++){ soma += A[i]*B[i]; } pthread_mutex_lock(&s); produto_escalar += soma; pthread_mutex_unlock(&s); } void imprime_vet(double* A, int n){ int i; for(i=0; i<n; i++){ printf("%.0lf ", A[i]); } printf("\\n"); } int main(){ int i; pthread_t threads[2]; TArgs parametros[2]; srand(time(0)); A = (double*) malloc(sizeof(double)*6); B = (double*) malloc(sizeof(double)*6); for(i=0; i<6; i++){ A[i] = rand() % 10; B[i] = rand() % 10; } for(i=0; i<2; i++){ parametros[i].id = i; pthread_create(&threads[i], 0, trabalhador, (void*)&parametros[i]); } for(i=0; i<2; i++){ pthread_join(threads[i], 0); } printf("A:\\n\\t"); imprime_vet(A, 6); printf("B:\\n\\t"); imprime_vet(B, 6); printf("Produto Escalar: %.2lf\\n", produto_escalar); return 0; }
1
#include <pthread.h> static pthread_mutex_t mtxCpt; static FILE* f; static pthread_mutex_t mtxAffichage; static int get_prime_factors(uint64_t n,uint64_t* factors) { uint64_t i; int nb_factors=0; if(n!=1) { uint64_t fin = n; for( i=2 ; i<=fin && n!=1 ; i++) { while(n%i == 0) { factors[nb_factors]=i; nb_factors++; n/=i; } } } return nb_factors; } static void print_prime_factors(uint64_t n) { uint64_t factors[63]; int j,k; k=get_prime_factors(n,factors); pthread_mutex_lock(&mtxAffichage); printf("%ju: ",n); for(j=0; j<k; j++) { printf("%ju ",factors[j]); } pthread_mutex_unlock(&mtxAffichage); printf("\\n"); } static void * gestion_threads(void * np) { char ligne [50]; pthread_mutex_lock(&mtxCpt); while(fgets(ligne,sizeof(ligne),f) !=0) { pthread_mutex_unlock(&mtxCpt); uint64_t n = (uint64_t)atoll(ligne); print_prime_factors(n); pthread_mutex_lock(&mtxCpt); } pthread_mutex_unlock(&mtxCpt); return 0; } int main(void) { pthread_t thread1; pthread_t thread2; pthread_mutex_init(&mtxCpt, 0); f= fopen("small.txt", "r"); pthread_create(&thread1, 0, gestion_threads, 0 ); pthread_create(&thread2, 0, gestion_threads, 0 ); pthread_join(thread1, 0); pthread_join(thread2, 0); fclose(f); return 0; }
0
#include <pthread.h> int* contador; pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; void* Contagem(void* arqid){ int input, fid = *((int *)arqid); FILE* f; char FileName[10]; sprintf(FileName,"%d.in",fid); f = fopen(FileName,"rt"); do{ input = -1; fscanf(f," %d",&input); if(input != -1){ pthread_mutex_lock(&mymutex); contador[input]++; pthread_mutex_unlock(&mymutex); } }while(input != -1); fclose(f); pthread_exit(0); } int main(){ int i,j,k,soma=0,rc,NumArq,NumThread,NumProd; printf("Num de Arquivos: "); scanf(" %d",&NumArq); printf("Num de Threads: "); scanf(" %d",&NumThread); printf("Num de Produtos: "); scanf(" %d",&NumProd); pthread_t threads[NumThread]; int* id[NumArq]; contador = (int*) malloc(NumProd*sizeof(int)); for(i=0;i<NumProd;i++) contador[i] = 0; for(i=0;i<NumArq;i++){ id[i] = (int*) malloc(sizeof(int)); *id[i] = i+1; rc = pthread_create(&threads[i%NumThread],0,Contagem,(void*) id[i]); if (rc){ printf("ERRO; código de retorno é %d\\n", rc); exit(-1); } } for(k=0;k<NumArq;k++){ pthread_join(threads[k%NumThread], 0); } float percent[NumProd]; for(j=0;j<NumProd;j++){ soma += contador[j]; } printf("\\nTotal de produtos lidos: %d\\n",soma); for(j=0;j<NumProd;j++){ percent[j]=((float)(100*contador[j]))/soma; printf("Percentual do produto %d: %7.3f%%\\n",j,percent[j]); } pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex_in_circle; int in_circle = 0; void* calculate_PI(void* arg) { int i, in_circle_loc = 0; double x, y, point; int *p = (int*)arg; for(i = 0; i < *p; i++) { x = (double)rand() / 32767; y = (double)rand() / 32767; point = x*x + y*y; if (point <= 1.0) in_circle_loc++; } pthread_mutex_lock(&mutex_in_circle); in_circle += in_circle_loc; pthread_mutex_unlock(&mutex_in_circle); pthread_exit(0); } int main(int argc, char* argv[]) { pthread_t threads[4]; pthread_attr_t attribute; int i, rc, num_of_points; double x, y, point, pi; int in_circle_main = 0; printf("Unesite broj tacaka za generisanje:\\n"); scanf("%d", &num_of_points); pthread_mutex_init(&mutex_in_circle, 0); pthread_attr_init(&attribute); pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE); for(i = 0; i < 4; i++) { rc = pthread_create(&threads[i], &attribute, calculate_PI, (void*)&num_of_points); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(-1); } } for(i = 0; i < num_of_points; i++) { x = (double)rand() / 32767; y = (double)rand() / 32767; point = x*x + y*y; if (point <= 1.0) in_circle_main++; } for (i = 0; i < 4; i++) { rc = pthread_join(threads[i], 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_join() je: %d", rc); exit(-2); } } pi = (4.0 * (in_circle+in_circle_main)) / (double)((4 + 1)*num_of_points); printf("Vrednost broja PI je: %lf\\n", pi); pthread_attr_destroy(&attribute); pthread_mutex_destroy(&mutex_in_circle); return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> int somme; pthread_mutex_t mutex_somme = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_cond = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int cpt = 0; pthread_t tid[10]; pthread_t tid2; void* affiche(){ pthread_cond_wait(&cond,&mutex_cond); pthread_mutex_unlock(&mutex_cond); printf("Valeur final : %d\\n", somme); return 0; } void* func_thread(){ int alea = (int) (10*((double)rand())/ 32767); srand(pthread_self()); printf("%d\\n",alea); pthread_mutex_lock(&mutex_somme); somme += alea; cpt++; pthread_mutex_unlock(&mutex_somme); if(cpt == 10){ pthread_mutex_lock(&mutex_cond); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex_cond); } pthread_exit((void*)0); return 0; } int main(){ int status; int i; int* pt_ind; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_mutex_lock(&mutex_cond); for(i=0; i<10; i++){ pt_ind = (int*)malloc(sizeof(i)); *pt_ind = i; pthread_create(&tid[i], &attr, func_thread, (void*)*pt_ind); pthread_detach(tid[i]); } pthread_create(&tid2, 0, affiche, (void*)*pt_ind); pthread_join(tid2, (void**)&status); free(pt_ind); pthread_mutex_destroy(&mutex_somme); pthread_mutex_destroy(&mutex_cond); pthread_cond_destroy(&cond); return 0; }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lockAir = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condTravelers=PTHREAD_COND_INITIALIZER,condAirPlane=PTHREAD_COND_INITIALIZER,condTravelersDis = PTHREAD_COND_INITIALIZER; int nrOfTrav=0; int N,MAX; void *travelers(void *args) { int id=-1; id = *((int *)args); pthread_mutex_lock(&lock); if(nrOfTrav >= MAX) { pthread_cond_wait(&condTravelers,&lock); } nrOfTrav++; pthread_mutex_unlock(&lock); printf("Boarding person %d\\n",id); if(nrOfTrav == MAX) { pthread_cond_signal(&condAirPlane); } } void *airplane(void *args) { if(pthread_mutex_lock(&lockAir)!=0) { printf("Cannot take lock"); } printf("Taking off\\n"); sleep(3); printf("landed\\n"); pthread_cond_signal(&condTravelers); pthread_mutex_unlock(&lockAir); } int main(int argc,char* argv[]) { if(argc!=3) { perror("Invalid number of parameters"); exit(1); } N = atoi(argv[1]); MAX = atoi(argv[2]); pthread_t travs[N]; for(int i=1; i<=N; i++) { pthread_create(&travs[i],0,travelers,&i); sleep(1); } for(int i=1; i<=N; i++) { if(pthread_join(travs[i],0)!=0) { perror("Error joining threads"); exit(2); } } pthread_t plane; pthread_create(&plane,0,airplane,&MAX); pthread_join(plane,0); }
1
#include <pthread.h> pthread_mutex_t counter_mutex; int counter = 0; char *file_list[] = {"10G.data1","10M.data1","10G.data2","10M.data2","10G.data3","10M.data3","10G.data4","10M.data4","10G.data5","10M.data5","10G.data6","10M.data6","10G.data7","10M.data7","10G.data8","10M.data8","10G.data9","10M.data9","10G.data10","10M.data10" }; int N = 20; void *xferFile(void *vargp); int main(){ pthread_t threads[4]; pthread_mutex_init(&counter_mutex, 0); printf("Start transferring ... \\n"); int tn; for(tn = 0 ; tn < 4 ; tn++){ pthread_create(&threads[tn], 0, xferFile, &tn); } for(tn = 0 ; tn < 4 ; tn++){ pthread_join(threads[tn], 0); } printf("All transfers finished. \\n"); pthread_mutex_destroy(&counter_mutex); exit(0); } char str1[] = "globus-url-copy ftp://cc120.fst.alcf.anl.gov:37119/gpfs/mira-fs1/projects/Concerted_Flows/EPSON/md5_data/"; char str2[] = "globus-url-copy -sync -sync-level 3 ftp://cc120.fst.alcf.anl.gov:37119/gpfs/mira-fs1/projects/Concerted_Flows/EPSON/md5_data/"; char str3[] = " ftp://cc112.fst.alcf.anl.gov:33825/gpfs/mira-fs1/projects/Concerted_Flows/EPSON/checksum_tests/"; void *xferFile(void *arg){ int tn = *(int *)(arg); char *xfer_cmd; char *cksum_cmd; int xfer_len; int cksum_len; int local_counter = 0; char filename[50]; while(counter < N){ printf("%d : %p \\n", counter, (void *)pthread_self()); pthread_mutex_lock(&counter_mutex); local_counter = counter; counter = counter + 1; pthread_mutex_unlock(&counter_mutex); char filename[50]; memset(filename, 0 , sizeof(filename)); strcpy(filename, file_list[local_counter]); xfer_len = strlen(str1) + strlen(str3) + strlen(filename) + 1; if((xfer_cmd = malloc(xfer_len)) != 0){ memset(xfer_cmd, 0 , xfer_len); strcat(xfer_cmd, str1); strcat(xfer_cmd, filename); strcat(xfer_cmd, str3); }else{ exit(0); } cksum_len = strlen(str2) + strlen(filename) + strlen(str3) + strlen(filename) + 1; if((cksum_cmd = malloc(cksum_len)) != 0){ memset(cksum_cmd, 0 , cksum_len); strcat(cksum_cmd, str2); strcat(cksum_cmd, filename); strcat(cksum_cmd, str3); strcat(cksum_cmd, filename); }else{ exit(0); } system(xfer_cmd); system(cksum_cmd); free(xfer_cmd); free(cksum_cmd); } return 0; }
0
#include <pthread.h> pthread_mutex_t buflock; static char mt_cmd[1000], mt_result[1000]; int read_ok=0; pthread_cond_t cond_read_ok; pthread_mutex_t lock_read_ok; int parent_mt( void ) { while(1){ char result[1000]; char *p = readline( "aho>" ); if( p ==0 )exit(0); add_history( p ); pthread_mutex_lock( &buflock ); strcpy( mt_cmd , p ); pthread_mutex_unlock( &buflock ); pthread_mutex_lock( &lock_read_ok ); while( read_ok != 1 ){ pthread_cond_wait( &cond_read_ok , &lock_read_ok ); } pthread_mutex_lock( &buflock ); printf( "result: <%s>\\n", mt_result ); pthread_mutex_unlock( &buflock ); read_ok = 0; pthread_mutex_unlock( &lock_read_ok ); } return 0; } int child_mt( void ) { int k = 0; while(1){ char buf[100]; usleep(200*1000); pthread_mutex_lock( &buflock ); if( mt_cmd[0] ){ int a; for(a=0;a<3;a++){sleep(1);fprintf( stderr,".");} sprintf( mt_result , "%s:%d", mt_cmd,k++ ); pthread_mutex_lock( &lock_read_ok ); read_ok = 1; pthread_cond_broadcast( &cond_read_ok ); pthread_mutex_unlock( &lock_read_ok ); mt_cmd[0] = 0; } pthread_mutex_unlock( &buflock ); } return 0; } int main( int argc, char **argv ) { pthread_t pt , ct; pthread_attr_t pa , ca; pthread_attr_init( &pa ); pthread_attr_init( &ca ); pthread_mutex_init( &buflock , 0 ); pthread_mutex_init( &lock_read_ok , 0 ); pthread_cond_init( &cond_read_ok , 0 ); pthread_create( &pt , &pa , (void*) &parent_mt , (void*)0 ); pthread_create( &ct , &ca , (void*) &child_mt , (void*) 0 ); pthread_join( pt , 0 ); pthread_join( ct , 0 ); return 0; }
1
#include <pthread.h> int global_variable_count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void* IncrementVariable(void *id) { int i; int threadID = (int)id; printf("Starting IncrementVariable(): thread %d\\n", threadID); for (i=0; i < 5; i++) { pthread_mutex_lock(&count_mutex); global_variable_count++; if (global_variable_count == 8) { pthread_cond_signal(&count_threshold_cv); printf("IncrementVariable(): thread %d, count = %d Limit reached.\\n", threadID, global_variable_count); } printf("IncrementVariable(): thread %d, incrementing count, count = %d, unlocking mutex\\n", threadID, global_variable_count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void* WatchVariable(void *id) { int threadID = (int)id; printf("Starting WatchVariable(): thread %d\\n", threadID); pthread_mutex_lock(&count_mutex); while (global_variable_count < 8) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("WatchVariable(): thread %d Condition signal received.\\n", threadID); global_variable_count += 1000; printf("WatchVariable(): thread %d count now = %d.\\n", threadID, global_variable_count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i; pthread_t threads[3]; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_create(&threads[0], &attr, WatchVariable, (void *)1); pthread_create(&threads[1], &attr, IncrementVariable, (void *)2); pthread_create(&threads[2], &attr, IncrementVariable, (void *)3); for (i=0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Done.\\n"); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); return 1; }
0
#include <pthread.h> int x, N, n = 0; float xN, factN, resultado = 0.0; pthread_mutex_t tomar, poner; void *calculaXN (); void *calculaFactN (); int main(int argc, char *argv[]) { int i; pthread_t hilo_productor, hilo_consumidor; printf("\\n\\t\\tEste programa calcula el valor de e^x\\n\\n"); printf("\\t¿Qué valor deseas asignarle a la variable x? "); scanf("%d", &x); printf("\\n\\t¿Para cuántos términos deseas calcular la serie? (entre 0 y 10): "); scanf("%d", &N); if (N > 0 && N <= 10) { pthread_mutex_init(&tomar, 0); pthread_mutex_init(&poner, 0); pthread_mutex_unlock(&tomar); pthread_mutex_lock(&poner); pthread_create(&hilo_productor, 0, (void*) calculaFactN, 0); pthread_create(&hilo_consumidor, 0, (void*) calculaXN, 0); pthread_join(hilo_productor, 0); pthread_join(hilo_consumidor, 0); pthread_mutex_destroy(&tomar); pthread_mutex_destroy(&poner); printf("\\n\\t\\te^%d = %f\\n", x, resultado); } else printf("\\n\\t\\tIngresaste un valor incorrecto.\\n"); return 0; } void *calculaXN () { while (n < N) { pthread_mutex_lock(&poner); xN = pow((double)x, (double)n); n ++; pthread_mutex_unlock(&tomar); resultado += xN/factN; } pthread_exit(0); } void *calculaFactN () { int i; while (n < N) { pthread_mutex_lock(&tomar); factN = 1.0; for (i = 1; i <= n; i++) factN *= i; pthread_mutex_unlock(&poner); } pthread_exit(0); }
1
#include <pthread.h> static void process_function_actual(int job_type); static int process_judege(struct Job *job); static void *process_function(void*); static int hash_index; static int get_user_pass(const int len, const char *source) { const char *pointer = source; int ret, new_len = len; int ovector[300]; ret = pcre_match("^(\\\\w+?)\\\\s+login\\\\s+(.+?@.+?)\\\\s+\\"(.+)\\"", pointer, new_len, ovector, 300, PCRE_MULTILINE|PCRE_CASELESS|PCRE_NEWLINE_CRLF); if ( ret != 4 ) return ret; printf("user : %.*s\\n", ovector[5]-ovector[4], pointer+ovector[4]); printf("pass : %.*s\\n", ovector[7]-ovector[6], pointer+ovector[6]); return ret; } static int is_response_err(const char *sign, int len) { int ovector[300]; if ( pcre_match("ok", sign, len, ovector, 300, PCRE_CASELESS) == 1 ) return 0; else return 1; } static void tackle_command(const char *cmd, const char *ptr, int len, int *ovector, int ov_size) { char command[256], response[256], *tag; int ret, head, tail; sprintf(command, "^(\\\\w+?)\\\\s+%s\\\\s+\\\\d+\\\\s+\\\\" "(.+(?:body|all|fast|full|bodystructure|envelope).+\\\\)\\r\\n", cmd); do { struct Email_info email; email_info_init(&email); ret = pcre_match( command, ptr, len, ovector, ov_size, PCRE_MULTILINE|PCRE_CASELESS| PCRE_NEWLINE_CRLF ); if ( ret != 2 ) break; head = ovector[1]; tag = (char*)malloc( (ovector[3]-ovector[2]+1) * sizeof(char) ); memset(tag, '\\0', ovector[3]-ovector[2]+1); memcpy(tag, ptr + ovector[2], ovector[3]-ovector[2]); memset(response, '\\0', sizeof(response)); sprintf(response, "^%s\\\\s+(ok|no|bad).*?\\r\\n", tag); free(tag); ret = pcre_match( response, ptr, len, ovector, ov_size, PCRE_MULTILINE|PCRE_CASELESS| PCRE_NEWLINE_CRLF ); if ( is_response_err( ptr+ovector[2], ovector[3]-ovector[2]) ) { ptr += head; len -= head; continue; } tail = ovector[0]; ret = pcre_match("\\\\((.*)\\\\)", ptr + head, tail - head, ovector, ov_size, PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL| PCRE_NEWLINE_CRLF); if ( ret != 2 ) { ptr += head; len -= head; continue; } strcpy(email.category,"Web Email"); email.role = 0; mime_entity(&email, ptr + head + ovector[2], ovector[3] - ovector[2]); sql_factory_add_email_record(&email, hash_index); email_info_free(&email); ptr += tail; len -= tail; } while ( len != 0 ); } static int analysis(const int len, const char *source) { int ovector[300]; tackle_command("uid fetch", source, len, ovector, 300); tackle_command("fetch", source, len, ovector, 300); return 0; } extern void imap_analysis_init(){ register_job(JOB_TYPE_IMAP,process_function,process_judege,CALL_BY_TCP_DATA_MANAGE); } static void *process_function(void *arg){ int job_type = JOB_TYPE_IMAP; while(1){ pthread_mutex_lock(&(job_mutex_for_cond[job_type])); pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type])); pthread_mutex_unlock(&(job_mutex_for_cond[job_type])); process_function_actual(job_type); } return 0; } static void process_function_actual(int job_type){ struct Job_Queue private_jobs; private_jobs.front = 0; private_jobs.rear = 0; get_jobs(job_type,&private_jobs); struct Job current_job; time_t nowtime; struct tcp_stream *a_tcp; while(!jobqueue_isEmpty(&private_jobs)){ jobqueue_delete(&private_jobs,&current_job); hash_index = current_job.hash_index; get_user_pass(current_job.promisc->head->length,current_job.promisc->head->data); analysis(current_job.promisc->head->length,current_job.promisc->head->data); if(current_job.server_rev!=0){ wireless_list_free(current_job.server_rev); free(current_job.server_rev); } if(current_job.client_rev !=0){ wireless_list_free(current_job.client_rev); free(current_job.client_rev); } if(current_job.promisc != 0){ wireless_list_free(current_job.promisc); free(current_job.promisc); } } } static int process_judege(struct Job *job){ job->desport = 143; job->data_need = 4; return 1; }
0
#include <pthread.h> { int row_num; int col_num; int luggage; } tag; tag collection_box[4 * 9]; pthread_mutex_t ticket_lock = PTHREAD_MUTEX_INITIALIZER; void create_a_tag(int col, int row) { static int count = 0; collection_box[count].col_num = col; collection_box[count].row_num = row; collection_box[count++].luggage = 2; } void* ticketing_machine(void *have_luggage) { static int count = 0; pthread_mutex_lock(&ticket_lock); collection_box[count++].luggage = *((int *)have_luggage); printf("Running thread\\n"); sleep(rand() % 10); pthread_mutex_unlock(&ticket_lock); return 0; } int main(int argc, char** argv) { void* result; int i, j, num_of_threads, coff, luggage; i = j = coff = luggage = 0; if (argc != 2){ fprintf(stderr, "Usage: %s [number of people]\\n", argv[0]); fprintf(stderr, "Example: %s 25\\n", argv[0]); fprintf(stderr, "In the above example, 25 people will take the couch. 25 threads will be created.\\n"); return 1; } pthread_mutex_init(&ticket_lock, 0); num_of_threads = atoi(argv[1]); pthread_t threads[num_of_threads]; for (i = 0; i <= 9; i++){ for (j = 0; j <= 4; j++) create_a_tag(i + 1, j + 1); } for (i = 0; i < num_of_threads; i++){ if ((i % 5) == 0) coff = (rand() % 5) + i; luggage = (coff == i) ? 0 : 1 ; pthread_create(&threads[i], 0, ticketing_machine, (void*) &luggage); } for (i = 0; i < num_of_threads; i++){ pthread_join(threads[i], &result); } for (i = 0; i < 9 * 4; i++) printf("Col: %d, Row: %d, Lugguage: %d\\n", collection_box[i].col_num, collection_box[i].row_num, collection_box[i].luggage); return 0; }
1
#include <pthread.h> extern int global_port; extern int max_slave_server; static int active_ports=0; void push_thread(struct threadID * temp_thread) { pthread_mutex_lock(&mutex_variable); if(thread_header==0) { thread_header=temp_thread; thread_header->next=0; } else { temp_thread->next=thread_header; thread_header=temp_thread; } temp_thread->status=0; ++active_ports; pthread_mutex_unlock(&mutex_variable); } int intialize_thread() { int i; struct threadID *new_thread=0; for(i=0;i<max_slave_server;i++) { new_thread=malloc(sizeof(struct threadID)); if(new_thread==0) { printf("\\nMemory overflow"); return 0; } else { new_thread->client.port=global_port+1+i; if(sem_init(&(new_thread->binary_sem),0,0)==0) new_thread->status=0; pthread_create(&(new_thread->ID),0,handle,new_thread); if(common_connect_server(&host_ipaddress,&new_thread->client.server_socket,new_thread->client.port,(const char *)0)==0) { printf("\\n Not able to open connection"); return 1; } printf("\\n Able to open new port\\n"); push_thread(new_thread); } } return 1; } int activate_thread() { struct threadID * temp_thread; pthread_mutex_lock(&mutex_variable); if(thread_header==0) { pthread_mutex_unlock(&mutex_variable); return 0; } else { printf("\\n switching"); temp_thread=thread_header; thread_header=thread_header->next; } active_ports--; pthread_mutex_unlock(&mutex_variable); printf("\\n Unlocking"); sem_post(&(temp_thread->binary_sem)); } void cleanup_thread() { struct threadID *temp_thread; pthread_mutex_lock(&mutex_variable); while(thread_header!=0) { temp_thread=thread_header; thread_header=thread_header->next; SDLNet_TCP_Close(temp_thread->client.server_socket); pthread_cancel(temp_thread->ID); sem_destroy(&(temp_thread->binary_sem)); free(temp_thread); } if(thread_header==0) printf("\\n Great every thing is cleaned"); } int get_active_threads() { return active_ports; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; int my_id = (int)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %d, count = %d Threshold reached.", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %d, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); usleep(300); } pthread_exit(0); } void *watch_count(void *t) { int my_id = (int)t; printf("Starting watch_count(): thread %d\\n", my_id); pthread_mutex_lock(&count_mutex); if (count < 12) { printf("watch_count(): thread %d going into wait...\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %d Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %d count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[2], &attr, watch_count, (void *)t3); pthread_create(&threads[0], &attr, inc_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); exit(0); }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc,condp; int buffer=0; void *producer(void* ptr) { int i; for(i=1;i<=10000;i++) { pthread_mutex_lock(&the_mutex); while(buffer != 0) { pthread_cond_wait(&condp,&the_mutex); } buffer = i; printf("producer:%d\\n",buffer); pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void* consumer(void* ptr) { int i; for(i=1;i<=10000;i++) { pthread_mutex_lock(&the_mutex); while(buffer==0) { pthread_cond_wait(&condc,&the_mutex); } buffer = 0; printf("consumer:%d\\n",buffer); pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc,char** argv) { pthread_t pro,con; pthread_mutex_init(&the_mutex,0); pthread_cond_init(&condc,0); pthread_cond_init(&condp,0); pthread_create(&con,0,consumer,0); pthread_create(&pro,0,producer,0); pthread_join(pro,0); pthread_join(con,0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); return 0; }
0
#include <pthread.h> struct job { struct job* next; int num; }; struct job* job_queue; struct job* tail; 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++; } } 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"; } 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; } pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_function (void* arg){ int* n = (int *) arg; printf("*********************Soy el hilo %d**************************\\n", *n); while (1) { struct job* next_job; pthread_mutex_lock (&job_queue_mutex); if (job_queue == 0) next_job = 0; else { next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0) break; process_job (next_job, *n); free (next_job); } return (void*) 1; } int main (int argc, char *argv[]) { int list_lentgh; if (argc >= 2){ list_lentgh = atoi(argv[1]); printf("%s\\n", argv[1]); }else{ list_lentgh = 100; } job_queue = 0; job_queue = (struct job *) malloc(sizeof (struct job)); 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)); aux->next = tail; aux = aux->next; } 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); return 0; }
1
#include <pthread.h> struct rwlock_t { pthread_mutex_t rdlock; int count; pthread_mutex_t wrlock; }; int my_rwlock_init(struct rwlock_t *rwlock) { pthread_mutex_init(&rwlock->rdlock); rwlock->count = 0; pthread_mutex_init(&rwlock->wrlock); return 0; } int my_rwlock_rdlock(struct rwlock_t *rwlock) { if (pthread_mutex_trylock(&rwlock->rdlock)) { pthread_mutex_lock(&rwlock->wrlock); rwlock->count += 1; pthread_mutex_unlock(&rwlock->wrlock); } else { rwlock->count += 1; } return 0; } int my_rwlock_wrlock(struct rwlock_t *rwlock) { if (pthread_mutex_trylock(&rwlock->rwlock)) { } else { } return 0; } int my_rwlock_unlock(struct rwlock_t *rwlock) { } int my_rwlock_destroy(struct rwlock_t *rwlock) { } int main(int argc, char *argv[]) { return 0; }
0
#include <pthread.h> bool packet_queue_init(struct ff_packet_queue *q) { memset(q, 0, sizeof(struct ff_packet_queue)); if (pthread_mutex_init(&q->mutex, 0) != 0) goto fail; if (pthread_cond_init(&q->cond, 0) != 0) goto fail1; av_init_packet(&q->flush_packet.base); q->flush_packet.base.data = (uint8_t *)"FLUSH"; return 1; fail1: pthread_mutex_destroy(&q->mutex); fail: return 0; } void packet_queue_abort(struct ff_packet_queue *q) { pthread_mutex_lock(&q->mutex); q->abort = 1; pthread_cond_signal(&q->cond); pthread_mutex_unlock(&q->mutex); } void packet_queue_free(struct ff_packet_queue *q) { packet_queue_flush(q); pthread_mutex_destroy(&q->mutex); pthread_cond_destroy(&q->cond); av_free_packet(&q->flush_packet.base); } int packet_queue_put(struct ff_packet_queue *q, struct ff_packet *packet) { struct ff_packet_list *new_packet; new_packet = av_malloc(sizeof(struct ff_packet_list)); if (new_packet == 0) return FF_PACKET_FAIL; new_packet->packet = *packet; new_packet->next = 0; pthread_mutex_lock(&q->mutex); if (q->last_packet == 0) q->first_packet = new_packet; else q->last_packet->next = new_packet; q->last_packet = new_packet; q->count++; q->total_size += new_packet->packet.base.size; pthread_cond_signal(&q->cond); pthread_mutex_unlock(&q->mutex); return FF_PACKET_SUCCESS; } int packet_queue_put_flush_packet(struct ff_packet_queue *q) { return packet_queue_put(q, &q->flush_packet); } int packet_queue_get(struct ff_packet_queue *q, struct ff_packet *packet, bool block) { struct ff_packet_list *potential_packet; int return_status; pthread_mutex_lock(&q->mutex); while (1) { potential_packet = q->first_packet; if (potential_packet != 0) { q->first_packet = potential_packet->next; if (q->first_packet == 0) q->last_packet = 0; q->count--; q->total_size -= potential_packet->packet.base.size; *packet = potential_packet->packet; av_free(potential_packet); return_status = FF_PACKET_SUCCESS; break; } else if (!block) { return_status = FF_PACKET_EMPTY; break; } else { pthread_cond_wait(&q->cond, &q->mutex); if (q->abort) { return_status = FF_PACKET_FAIL; break; } } } pthread_mutex_unlock(&q->mutex); return return_status; } void packet_queue_flush(struct ff_packet_queue *q) { struct ff_packet_list *packet; pthread_mutex_lock(&q->mutex); for (packet = q->first_packet; packet != 0; packet = q->first_packet) { q->first_packet = packet->next; av_free_packet(&packet->packet.base); if (packet->packet.clock != 0) ff_clock_release(&packet->packet.clock); av_freep(&packet); } q->last_packet = q->first_packet = 0; q->count = 0; q->total_size = 0; pthread_mutex_unlock(&q->mutex); }
1
#include <pthread.h> static int _sd; static pthread_mutex_t sd_mutex; void init_gui_trans(int sd){ int val = 1; ioctl(sd, FIONBIO, &val); pthread_mutex_init(&sd_mutex,0); _sd = sd; } void gui_send(int x,int y){ int buf[2]; buf[0] = x; buf[1] = y; pthread_mutex_lock(&sd_mutex); if(send(_sd, buf, sizeof(int)*2,0) < 0){ if(errno != EAGAIN) die("sendto"); } pthread_mutex_unlock(&sd_mutex); } int* gui_recv(){ static int buf[2]; int i; pthread_mutex_lock(&sd_mutex); if((i = recv(_sd, buf, sizeof(int)*2, 0)) < 0){ if(errno != EAGAIN) die("recvfrom"); } pthread_mutex_unlock(&sd_mutex); if(i != 2*sizeof(int)) return 0; return buf; }
0
#include <pthread.h> pthread_mutex_t lock; int counter = 0; int lagerGrosse = 10; int itemBuffer[10]; void producer(void *ptr); void consumer(void *ptr); void insertItem(int item); void removeItem(int *item); void producer(void *tid) { while(1) { int event; scanf("%d",&event); if(event == 1) { pthread_mutex_lock(&lock); int item = rand()+1; printf("\\n Produktion gestartet\\n"); insertItem(item); printf("\\n Produktion beendet\\n"); printf("-------------------------\\n"); pthread_mutex_unlock(&lock); } } } void consumer(void *tid) { while(1) { sleep(2); pthread_mutex_lock(&lock); int item; printf("\\n Konsum gestartet\\n"); removeItem(&item); printf("\\n Konsum beendet\\n"); printf("-------------------------\\n"); pthread_mutex_unlock(&lock); } } void insertItem(int item){ if (counter < lagerGrosse){ itemBuffer[counter] = item; counter ++; printf("\\n Item zum Lager hinzugefügt: %d items im Lager\\n",counter); }else{ printf("\\n Lager ist Voll\\n"); } } void removeItem(int *item){ if (counter > 0){ *item = itemBuffer[counter-1]; counter --; printf("\\n Item konsumiert: %d items im Lager\\n", counter); }else{ printf("\\n Lager ist leer\\n"); *item = 0; } } int main(void) { int id[2]; pthread_t thread_1; pthread_t thread_2; int err; pthread_mutex_init(&lock, 0); err = pthread_create(&thread_1, 0, (void *) &producer, (void *) &id[0]); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); err = pthread_create(&thread_2, 0, (void *) &consumer, (void *) &id[1]); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); pthread_join(thread_1, 0); pthread_join(thread_2, 0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> int key, value; struct __node_t * next; } node_t; node_t * head; pthread_mutex_t lock; pthread_mutexattr_t __lock_attr; } list_t; void list_init(list_t *lst) { lst->head = 0; Pthread_reentrant_mutex_init(&lst->lock, &lst->__lock_attr); } int list_insert(list_t *lst, int key, int value) { Pthread_mutex_lock(&lst->lock); node_t *new = malloc(sizeof(node_t)); if(new == 0) { fprintf(stderr, "malloc fail\\n"); Pthread_mutex_unlock(&lst->lock); return -1; } new->key = key; new->value = value; new->next = lst->head; lst->head = new; Pthread_mutex_unlock(&lst->lock); return 0; } int list_lookup(list_t *lst, int key, int *out_ptr) { Pthread_mutex_lock(&lst->lock); node_t *curr = lst->head; while (curr != 0) { if(curr->key == key) { if (out_ptr != 0) { *out_ptr = curr->value; } pthread_mutex_unlock(&lst->lock); return 0; } curr = curr->next; } Pthread_mutex_unlock(&lst->lock); return -1; } void list_iter (list_t *lst) { Pthread_mutex_lock(&lst->lock); node_t * curr = lst->head; while(curr != 0) { printf("key:%d value:%d\\n", curr->key, curr->value); curr = curr->next; } } int main(int argc, char * argv[]) { list_t lst; list_init(&lst); for(int i = 0; i < 10000; i++) { int key = i, value = 3 * i + 1; list_insert(&lst, key, value); } system("PAUSE"); list_iter(&lst); int key = 25; if (list_lookup(&lst, key, 0) == 0) { fprintf(stdout, "%d is in the list!\\n", key); } else { fprintf(stdout, "%d is NOT in the list!\\n", key); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_barrier_t barrier; int flag =0 ; void * pthread_a(void *arga){ fprintf(stderr ,"start a barrier\\n"); pthread_barrier_wait (&barrier); fprintf(stderr,"1 - flag a %ld\\n",flag); pthread_barrier_wait (&barrier); fprintf(stderr,"2 - flag a %ld\\n",flag); pthread_mutex_lock(&mutex); flag = 1; fprintf(stderr,"flag a %ld\\n",flag); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); fprintf(stderr , "a finish !\\n"); sleep(1); pthread_exit(0); } void * pthread_b(void *argb){ fprintf(stderr ,"start b barrier\\n"); pthread_barrier_wait (&barrier); fprintf(stderr,"1 - flag b %ld\\n",flag); pthread_barrier_wait (&barrier); fprintf(stderr,"2 - flag b %ld\\n",flag); pthread_mutex_lock(&mutex); fprintf(stderr,"flag b %ld\\n",flag); while(flag != 1) pthread_cond_wait(&cond,&mutex); flag = 2; fprintf(stderr,"flag b %ld\\n",flag); pthread_mutex_unlock(&mutex); fprintf(stderr , "b finish !\\n!"); pthread_exit(0); } int arg[2]={0}; int main(void) { pthread_t tid[2]; int ret; pthread_barrier_init(&barrier, 0 ,3); ret = pthread_create(&tid[0], 0,pthread_a, 0); if (ret != 0 ) fprintf(stderr , "create a error\\n"); ret = pthread_create(&tid[1], 0,pthread_b, 0); if (ret != 0 ) fprintf(stderr , "create b error\\n"); fprintf(stderr ,"start main barrier\\n"); pthread_barrier_wait( &barrier ); fprintf(stderr ,"main barrier\\n"); sleep(5); fprintf(stderr ,"5 sec main barrier\\n"); pthread_barrier_wait( &barrier ); pthread_join(tid[0],0); pthread_join(tid[1],0); sleep(1); fprintf(stderr , "main exit ! \\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int thread_num; int* counter; pthread_t *thread; int *mem = 0; int sum = 0; int itr = 1024 / 16; void external_calculate(void* arg) { int i = 0, j = 0, k = 0; int n = *((int*) arg); for (k = n; k < 10; k += thread_num) { char a[3]; char path[20] = "./record/"; sprintf(a, "%d", k); strcat(path, a); FILE *f; f = fopen(path, "r"); if (!f) { printf("failed to open file %s, please run ./genRecord.sh first\\n", path); exit(0); } for (i = 0; i < itr; ++i) { for (j = 0; j < 4; ++j) { fscanf(f, "%d", &mem[k*4 + j]); pthread_mutex_lock(&mutex); sum += mem[k*4 + j]; pthread_mutex_unlock(&mutex); } } fclose(f); } } void verify() { int i = 0, j = 0, k = 0; char a[3]; char path[20] = "./record/"; sum = 0; memset(mem, 0, 160); for (k = 0; k < 10; ++k) { strcpy(path, "./record/"); sprintf(a, "%d", k); strcat(path, a); FILE *f; f = fopen(path, "r"); if (!f) { printf("failed to open file %s, please run ./genRecord.sh first\\n", path); exit(0); } for (i = 0; i < itr; ++i) { for (j = 0; j < 4; ++j) { fscanf(f, "%d\\n", &mem[k*4 + j]); sum += mem[k*4 + j]; } } fclose(f); } printf("verified sum is: %d\\n", sum); } void sig_handler(int signum) { } int main(int argc, char **argv) { int i = 0; if (argc == 1) { thread_num = 2; } else { if (argv[1] < 1) { printf("enter a valid thread number\\n"); return 0; } else thread_num = atoi(argv[1]); } counter = (int*)malloc(thread_num*sizeof(int)); for (i = 0; i < thread_num; ++i) counter[i] = i; thread = (pthread_t*)malloc(thread_num*sizeof(pthread_t)); mem = (int*)malloc(160); memset(mem, 0, 160); pthread_mutex_init(&mutex, 0); for (i = 0; i < thread_num; ++i) pthread_create(&thread[i], 0, &external_calculate, &counter[i]); signal(SIGABRT, sig_handler); signal(SIGSEGV, sig_handler); for (i = 0; i < thread_num; ++i) pthread_join(thread[i], 0); printf("sum is: %d\\n", sum); pthread_mutex_destroy(&mutex); verify(); printf("sum is: %d\\n", sum); char* gaha = shalloc(13); gaha = "I don't know\\0"; printf("%c\\n", gaha[3]); free(gaha); free(mem); free(thread); free(counter); return 0; }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for(i=0; i<((400)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR:__VERIFIER_error(); } void *t2(void *arg) { int i; for(i=0; i<(400); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR:__VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR:__VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> static int vvprintf_init = 0; static pthread_mutex_t vvprintf_mutex = PTHREAD_MUTEX_INITIALIZER; static char msgbuf[1024*10]; static int vvprintf_socket; static struct sockaddr_in vvprintf_serveraddr; int vvprintf(const char *format,...) { va_list myargs; __builtin_va_start((myargs)); pthread_mutex_lock(&vvprintf_mutex); if(vvprintf_init == 0 ) { vvprintf_socket = socket(AF_INET,SOCK_DGRAM,0); vvprintf_serveraddr.sin_family = AF_INET; vvprintf_serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); vvprintf_serveraddr.sin_port = htons(12345); vvprintf_init = 1; } vsprintf(msgbuf,format,myargs); sendto(vvprintf_socket,msgbuf,strlen(msgbuf),0,(struct sockaddr *)&vvprintf_serveraddr,sizeof(struct sockaddr)); ; pthread_mutex_unlock(&vvprintf_mutex); return 0; }
0
#include <pthread.h> int arreglo[100000]; int total=0; int indice=0; pthread_mutex_t m1; pthread_mutex_t m2; void *PrintHello(void *threadid){ int *id_ptr, taskid; int miIndice; int parcial=0; id_ptr = (int *) threadid; taskid = *id_ptr; while(indice < 100000){ pthread_mutex_lock(&m1); miIndice = indice; indice++; pthread_mutex_unlock(&m1); parcial = parcial + arreglo[miIndice]; } printf("Hilo %d termine el ciclo, mi parcial es: %d\\n",taskid, parcial); pthread_mutex_lock(&m2); total = total + parcial; pthread_mutex_unlock(&m2); pthread_exit(0); } int main(){ pthread_t threads[2]; int *taskids[2]; int rc, t; pthread_mutex_init (&m1, 0); pthread_mutex_init (&m2, 0); for(t=0; t<100000; t++){ arreglo[t]=1; } arreglo[100000]=3; for(t=0;t<2;t++) { taskids[t] = (int *) malloc(sizeof(int)); *taskids[t] = t; rc = pthread_create(&threads[t], 0, PrintHello, (void *) taskids[t]); } for(t=0;t<2;t++){ pthread_join(threads[t],0); } printf("el total es: %d\\n", total); }
1
#include <pthread.h> void increase_actors(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); while (lock->flags & 3) { pthread_cond_wait(&lock->cond, &lock->mutex); } lock->flags+=4; pthread_mutex_unlock(&lock->mutex); } } void decrease_actors(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); lock->flags-=4; pthread_cond_broadcast(&lock->cond); pthread_mutex_unlock(&lock->mutex); } } int prepare_directory_exclusive(struct notifyfshm_directory_struct *directory, unsigned char locked) { int lockset=-1; struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { if (locked==0) pthread_mutex_lock(&lock->mutex); if ((lock->flags & 1) == 0) { lock->flags+=1; lockset=0; } if (locked==0) pthread_mutex_unlock(&lock->mutex); } return lockset; } void get_directory_exclusive(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); while (lock->flags>>3 > 1) { pthread_cond_wait(&lock->cond, &lock->mutex); } lock->flags+=2; pthread_mutex_unlock(&lock->mutex); } } void unlock_directory_exclusive(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); if (lock->flags & 1) lock->flags-=1; if (lock->flags & 2) lock->flags-=2; pthread_cond_broadcast(&lock->cond); pthread_mutex_unlock(&lock->mutex); } } void lock_directory(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) pthread_mutex_lock(&lock->mutex); } void unlock_directory(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) pthread_mutex_unlock(&lock->mutex); } void cond_wait_directory(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) pthread_cond_wait(&lock->cond, &lock->mutex); } void cond_broadcast_directory(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=0; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) pthread_cond_broadcast(&lock->cond); }
0
#include <pthread.h> pthread_mutex_t output_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t watchdog_thread; unsigned int watchdog_tick = 1; bool running = 0; void c_output(const char *format, ...) { if (!running) return; pthread_mutex_lock(&output_mutex); va_list args; __builtin_va_start((args)); vfprintf(stderr, format, args); ; pthread_mutex_unlock(&output_mutex); } static void *watchdog(void *dummy) { unsigned long last_blocked_counter = blocked_counter - 1; bool terminate; while (running) { terminate = 1; pthread_mutex_lock(&threads_list_mutex); if (terminate && list_empty(&threads_list.head)) terminate = 0; if (terminate && last_blocked_counter != blocked_counter) terminate = 0; if (terminate && check_liveness()) terminate = 0; pthread_mutex_unlock(&threads_list_mutex); if (terminate) { c_output("Deadlock detected, fixed interleaving is probably impossible. Perhaps synchronization is correct or you should adjust watchdog tick with $C_WATCHDOG_TICK. Publishing all events, finishing all blocks...\\n"); pthread_mutex_lock(&events_list_mutex); publish_all_events(); pthread_mutex_unlock(&events_list_mutex); pthread_mutex_lock(&blocks_list_mutex); finish_all_blocks(); pthread_mutex_unlock(&blocks_list_mutex); } last_blocked_counter = blocked_counter; sleep(watchdog_tick); } return 0; } void c_set_watchdog_tick(unsigned int tick) { watchdog_tick = tick; } void c_init() { char *disable_str; int disable_val; char *watchdog_tick_str; unsigned int new_watchdog_tick; disable_str = getenv("C_DISABLE"); if (disable_str && sscanf(disable_str, "%d", &disable_val) == 1) if (disable_val) return; running = 1; INIT_LIST_HEAD(&events_list.head); INIT_LIST_HEAD(&threads_list.head); INIT_LIST_HEAD(&blocks_list.head); watchdog_tick_str = getenv("C_WATCHDOG_TICK"); if (watchdog_tick_str && sscanf(watchdog_tick_str, "%u", &new_watchdog_tick) == 1) c_set_watchdog_tick(new_watchdog_tick); pthread_create(&watchdog_thread, 0, watchdog, 0); } void c_free() { if (!running) return; running = 0; pthread_join(watchdog_thread, 0); free_threads_list(); free_events_list(); free_blocks_list(); }
1
#include <pthread.h> int shared = 5; pthread_mutex_t lock; void sendreply(int replyfrompno,int replytopno,int ts) { FILE *ptr; if(replytopno==1) { ptr = fopen("file1.txt","a"); } if(replytopno==2) { ptr = fopen("file2.txt","a"); } if(replytopno==3) { ptr = fopen("file3.txt","a"); } fprintf(ptr,"%d %d\\n",replyfrompno,ts); fclose(ptr); } void *process1(void *val) { int replyfrom[4]={0}; int queue[3]={0}; int clockvalue = 0; int replyto[4]={0}; FILE *ptr1,*ptr2,*ptr3; pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt","r"); char line [1000]; int pno=0,ts=0,timefromotherprocess=0; while (!feof (ptr1)) { fscanf(ptr1,"%d %d",&pno,&ts); if(ts > 0 && (pno == 2 || pno == 3)) { if(ts > timefromotherprocess) timefromotherprocess = ts; } } if(clockvalue < timefromotherprocess) clockvalue = timefromotherprocess + 1; else clockvalue = clockvalue + 1; printf("file1 %d %d\\n",pno,ts); fclose(ptr1); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr2 = fopen("file2.txt","a"); fprintf(ptr2,"%d %d\\n",1,clockvalue); fclose(ptr2); ptr3 = fopen("file3.txt","a"); fprintf(ptr3,"%d %d\\n",1,clockvalue); fclose(ptr3); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt","r"); while (!feof (ptr1)) { int pno,ts; fscanf(ptr1,"%d %d",&pno,&ts); if(ts > 0 && (pno!=1)) { sendreply(1,pno,-ts); replyto[pno]=1; } printf("1file1 %d %d\\n",pno,ts); } fclose(ptr1); pthread_mutex_unlock(&lock); while(1) { pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt","r"); while (!feof (ptr1)) { int pno,ts; fscanf(ptr1,"%d %d",&pno,&ts); if(ts < 0) replyfrom[pno]=1; printf("1file1 %d %d\\n",pno,ts); } if(replyfrom[2] == 1 && replyfrom[3]==1) break; fclose(ptr1); pthread_mutex_unlock(&lock); sleep(2); } pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt","r"); while (!feof (ptr1)) { fscanf(ptr1,"%d %d",&pno,&ts); if(ts > 0 && (pno!=1)) { sendreply(1,pno,-ts); replyto[pno]=1; } printf("1file1 %d %d\\n",pno,ts); } fclose(ptr1); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); shared = shared + 10; printf("p1 did %d\\n",shared); pthread_mutex_unlock(&lock); } void *process2() { int reply[4]={0}; int clockvalue = 0; FILE *ptr1,*ptr2,*ptr3; pthread_mutex_lock(&lock); printf("--------------process2---------------\\n"); ptr2 = fopen("file2.txt","r"); char line [1000]; int pno=0,ts=0,timefromotherprocess=0; while (!feof (ptr2)) { fscanf(ptr2,"%d %d",&pno,&ts); if(ts > 0 && (pno == 1 || pno == 3)) { if(ts > timefromotherprocess) timefromotherprocess = ts; } } if(clockvalue < timefromotherprocess) clockvalue = timefromotherprocess + 1; else clockvalue = clockvalue + 1; printf("file2 %d %d\\n",pno,ts); fclose(ptr2); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process2---------------\\n"); ptr1 = fopen("file1.txt","a"); fprintf(ptr2,"%d %d\\n",2,clockvalue); fclose(ptr2); ptr3 = fopen("file3.txt","a"); fprintf(ptr3,"%d %d\\n",2,clockvalue); fclose(ptr3); pthread_mutex_unlock(&lock); while(1) { pthread_mutex_lock(&lock); printf("--------------process2---------------\\n"); ptr2 = fopen("file2.txt","r"); while (!feof (ptr2)) { int pno,ts; fscanf(ptr2,"%d %d",&pno,&ts); if(ts < 0) reply[pno]=1; printf("2file2 %d %d\\n",pno,ts); } if(reply[2] == 1 && reply[3]==1) break; fclose(ptr2); pthread_mutex_unlock(&lock); sleep(1); } pthread_mutex_lock(&lock); printf("--------------process2---------------\\n"); shared = shared + 10; printf("p1 did %d\\n",shared); pthread_mutex_unlock(&lock); } void *process3() { printf("--------------process3---------------\\n"); int reply[4]={0}; int clockvalue = 0; FILE *ptr1,*ptr2,*ptr3; pthread_mutex_lock(&lock); ptr3 = fopen("file3.txt","r"); char line [1000]; int pno=0,ts=0,timefromotherprocess=0; while (!feof (ptr3)) { fscanf(ptr3,"%d %d",&pno,&ts); if(ts > 0 && (pno == 2 || pno == 1)) { if(ts > timefromotherprocess) timefromotherprocess = ts; } } if(clockvalue < timefromotherprocess) clockvalue = timefromotherprocess + 1; else clockvalue = clockvalue + 1; printf("file3 %d %d\\n",pno,ts); fclose(ptr3); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process3---------------\\n"); ptr2 = fopen("file2.txt","a"); fprintf(ptr2,"%d %d\\n",3,clockvalue); fclose(ptr2); ptr1 = fopen("file1.txt","a"); fprintf(ptr1,"%d %d\\n",3,clockvalue); fclose(ptr1); pthread_mutex_unlock(&lock); while(1) { pthread_mutex_lock(&lock); printf("--------------process3---------------\\n"); ptr1 = fopen("file3.txt","r"); while (!feof (ptr1)) { int pno,ts; fscanf(ptr1,"%d %d",&pno,&ts); if(ts < 0) reply[pno]=1; printf("3file3 %d %d\\n",pno,ts); } if(reply[2] == 1 && reply[1]==1) break; fclose(ptr3); pthread_mutex_unlock(&lock); sleep(3); } pthread_mutex_lock(&lock); printf("--------------process3---------------\\n"); shared = shared + 10; printf("p1 did %d\\n",shared); pthread_mutex_unlock(&lock); } void main() { pthread_t pt[4]; int tid[4]; pthread_create(&pt[1], 0, process1,0); pthread_create(&pt[2], 0, process2,0); pthread_create(&pt[3], 0, process3,0); pthread_join(pt[1], 0); pthread_join(pt[2], 0); pthread_join(pt[3], 0); }
0
#include <pthread.h> pthread_mutex_t *mutex_init(){ pthread_mutex_t *m = calloc(1, sizeof(*m)); pthread_mutex_init(m, 0); return m; } void mutex_destroy(pthread_mutex_t *mutex){ free(mutex); } void mutex_lock(pthread_mutex_t *mutex){ if (mutex == 0) return; pthread_mutex_lock(mutex); } void mutex_unlock(pthread_mutex_t *mutex){ if (mutex == 0) return; pthread_mutex_unlock(mutex); } void mutex_deinit(pthread_mutex_t *mutex){ mutex_destroy(mutex); } sem_t *dedos_sem_init() { sem_t *s = calloc(1, sizeof(*s)); sem_init(s, 0, 0); return s; } void dedos_sem_destroy(sem_t *sem) { free(sem); } void dedos_sem_post(sem_t *sem) { if (sem == 0) return; sem_post(sem); } int dedos_sem_wait(sem_t *sem, int timeout) { struct timespec t; if (sem == 0) return 0; if (timeout < 0) { sem_wait(sem); } else { clock_gettime(CLOCK_REALTIME, &t); t.tv_sec += timeout / 1000; t.tv_nsec += (timeout % 1000) * 1000000; if (sem_timedwait(sem, &t) == -1) return -1; } return 0; } void *dedos_thread_create(void *(*routine)(void *), void *arg) { pthread_t *thread = calloc(1, sizeof(*thread)); if (pthread_create(thread, 0, routine, arg) == -1) return 0; return thread; }
1
#include <pthread.h> struct stack { char x[65535]; }; static pthread_mutex_t mutex[(503)]; static int data[(503)]; static struct stack stacks[(503)]; static void* thread(void *num) { int l = (int)(uintptr_t)num; int r = (l+1) % (503); int token; while(1) { pthread_mutex_lock(mutex + l); token = data[l]; if (token) { data[r] = token - 1; pthread_mutex_unlock(mutex + r); } else { printf("%i\\n", l+1); exit(0); } } } int main(int argc, char **argv) { int i; pthread_t cthread; pthread_attr_t stack_attr; if (argc != 2) exit(255); data[0] = atoi(argv[1]); pthread_attr_init(&stack_attr); for (i = 0; i < (503); i++) { pthread_mutex_init(mutex + i, 0); pthread_mutex_lock(mutex + i); pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack)); pthread_create(&cthread, &stack_attr, thread, (void*)(uintptr_t)i); } pthread_mutex_unlock(mutex + 0); pthread_join(cthread, 0); }
0
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static void *thr_primer(void *p); int main() { int i,j,mark; int err; pthread_t tid[4]; for(i = 0; i < 4 ; i++) { err = pthread_create(tid+i,0,thr_primer,(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); } 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 *thr_primer(void *p) { int i,j,mark; 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); 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); } pthread_exit(0); }
1
#include <pthread.h> int voti[5]; int votazioni_terminate[5]; pthread_mutex_t mutex_voti[5]; void inizializza_voti() { int i; for (i = 0; i < 5; i++) { voti[i] = 0; votazioni_terminate[i] = 0; } } void inizializza_mutex_voti() { int i; for (i = 0; i < 5; i++) { pthread_mutex_init(&mutex_voti[i], 0); } } void stampa_voti_finali_film() { int k; for (k = 0; k < 5; k++) { float voto_medio_film = (float)voti[k] / 10; int film_id = k + 1; printf("%d => %.1f", film_id, voto_medio_film); if (k < 5 - 1) { printf(" - "); } } } void *vota(void *thread_id_ptr) { long thread_id = (long)thread_id_ptr; if (0) printf("Thread %ld: partito...\\n", thread_id); int k; for (k = 0; k < 5; k++) { int film_id = k + 1; if (0) printf("Thread %ld: attendo accesso a voto film %d\\n", thread_id, film_id); pthread_mutex_lock(&mutex_voti[k]); if (0) printf("Thread %ld: accedo a voto film %d\\n", thread_id, film_id); int voto = (rand() % 10) + 1; voti[k] += voto; votazioni_terminate[k]++; float voto_medio_film = (float)voti[k] / (float)votazioni_terminate[k]; printf("Thread %ld: punteggio attuale film %d: %.1f\\n", thread_id, film_id, voto_medio_film); pthread_mutex_unlock(&mutex_voti[k]); } pthread_exit(0); } int main (int argc, char *argv[]) { srand(time(0)); if (0) printf("Inizializzo voti e relativi mutex\\n"); inizializza_voti(); inizializza_mutex_voti(); pthread_t thread_persone[10]; int i; for (i = 0; i < 10; i++) { if (0) printf("Main: creazione thread %d\\n", i); long thread_id = i; int result = pthread_create(&thread_persone[i], 0, vota, (void *)thread_id); if (result) { printf("Main: ERRORE - creazione thread %d: %d\\n", i, result); exit(-1); } } for (i = 0; i < 10; i++) { int result = pthread_join(thread_persone[i], 0); if (result) { if (0) printf("Main: ERRORE - attesa thread %d: %d\\n", i, result); } else { if (0) printf("Main: Thread %d terminato\\n", i); } } if (0) printf("Main: Tutti i thread terminati\\n\\n\\n"); printf("Main: Risultato finale sondaggio\\n"); stampa_voti_finali_film(); printf("\\n\\n\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t g_mutex; pthread_cond_t g_cond; char buf[5]; int count; } buffer_t; buffer_t g_share = {"", 0}; char g_ch = 'A'; void* producer( void *arg ) { printf( "Producer starting.\\n" ); while( g_ch != 'Z' ) { pthread_mutex_lock( &g_mutex ); if( g_share.count < 5 ) { g_share.buf[g_share.count++] = g_ch++; printf( "Prodcuer got char[%c]\\n", g_ch - 1 ); if( 5 == g_share.count ) { printf( "Producer signaling full.\\n" ); pthread_cond_signal( &g_cond ); } } pthread_mutex_unlock( &g_mutex ); } printf( "Producer exit.\\n" ); return 0; } void* consumer( void *arg ) { int i; printf( "Consumer starting.\\n" ); while( g_ch != 'Z' ) { pthread_mutex_lock( &g_mutex ); printf( "Consumer waiting\\n" ); pthread_cond_wait( &g_cond, &g_mutex ); printf( "Consumer writing buffer\\n" ); for( i = 0; g_share.buf[i] && g_share.count; ++i ) { putchar( g_share.buf[i] ); --g_share.count; } putchar('\\n'); pthread_mutex_unlock( &g_mutex ); } printf( "Consumer exit.\\n" ); return 0; } int main( int argc, char *argv[] ) { pthread_t ppth, cpth; pthread_mutex_init( &g_mutex, 0 ); pthread_cond_init( &g_cond, 0 ); pthread_create( &cpth, 0, consumer, 0 ); pthread_create( &ppth, 0, producer, 0 ); pthread_join( ppth, 0 ); pthread_join( cpth, 0 ); pthread_mutex_destroy( &g_mutex ); pthread_cond_destroy( &g_cond ); return 0; }
1
#include <pthread.h> int id; double a; double b; double step; } job; double result = 0; pthread_mutex_t lock; void* calc(void *args); int main(int argc, char** argv) { assert(argc == 3); int p = atoi(argv[1]); int n = atoi(argv[2]); assert(p > 0); assert(n > 0); const int thread_cnt = (n > p ? p : n); const double a = 0, b = 1; double step = (b - a) / n; double chunk = (b - a) / thread_cnt; pthread_t* thread_pool = (pthread_t*)malloc(thread_cnt * sizeof(pthread_t)); if (pthread_mutex_init(&lock, 0) != 0) { perror("pthread_mutex_init failure"); return 1; } fprintf(stderr, "Func.: Sin(x)\\nInt.: [%f, %f]\\n", a, b); fprintf(stderr, "Step: %f\\n", step); fprintf(stderr, "Chunk: %f\\n", chunk); for (int i = 0; i < thread_cnt; ++i) { job* j = (job*)malloc(sizeof(job)); j->id = i; j->a = a + i * chunk; j->b = (a + (i + 1) * chunk > b ? b : a + (i + 1) * chunk); j->step = step; if (pthread_create(thread_pool + i, 0, &calc, (void*)j) != 0) { perror("pthread_create failure"); return 1; } } for (int i = 0; i < thread_cnt; ++i) { pthread_join(thread_pool[i], 0); } if (pthread_mutex_destroy(&lock) != 0) { perror("pthread_mutex_destroy failure"); return 1; } free(thread_pool); fprintf(stderr, "Result: %f\\n", result); return 0; } void* calc(void* args) { job* j = (job*) args; double a = j->a; double b = j->b; double step = j->step; double part = 0; while (a < b) { part += step * (sin(a) + sin(a + step)) / 2; a += step; } pthread_mutex_lock(&lock); result += part; pthread_mutex_unlock(&lock); free(args); return 0; }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; }DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod (void *arg) { int i,start,end,offset,len; double mysum,*x,*y; offset=(int)arg; len=dotstr.veclen; start = offset*len; end=start+len; x=dotstr.a; y=dotstr.b; mysum=0; for(i=start;i<end;i++) { mysum+=(x[i]*y[i]); } pthread_mutex_lock(&mutexsum); dotstr.sum+=mysum; pthread_mutex_unlock(&mutexsum); pthread_exit((void*)0); } int main(int argc,char *argv[]) { int i; double *a,*b; void *status; pthread_attr_t attr; a=(double*)malloc(4*100*sizeof(double)); b=(double*)malloc(4*100*sizeof(double)); for(i=0;i<100*4;i++) { a[i]=1.0; b[i]=a[i]; } dotstr.veclen=100; dotstr.a=a; dotstr.b=b; dotstr.sum=0; pthread_mutex_init(&mutexsum,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i],&attr,dotprod,(void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i],&status); } printf("Sum = %f \\n",dotstr.sum); free(a); free(b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> char _getch() { struct termios old, new; char ch; tcgetattr(0, &old); new = old; new.c_lflag &= ~(ICANON | ECHO); tcsetattr(0, TCSANOW, &new); ch = getchar(); tcsetattr(0, TCSANOW, &old); return ch; } void* printThreads(void* data_temp) { struct Data data; data = *((struct Data*)data_temp); free(data_temp); while(1) { pthread_mutex_lock(&(data.mutex)); usleep(200000); printf("thread number: %d\\n", data.count); pthread_mutex_unlock(&(data.mutex)); } } void createNewThread(struct Data *data, struct Stack **stack) { data->count++; struct Data* data_temp = (struct Data*)malloc (sizeof(struct Data)); *data_temp = *data; if (pthread_create(&(data->thread), 0, &printThreads, (void*)data_temp)){ perror("pthread_create error"); exit(1); } else push(&*stack, *data); } void closeLastThread(struct Stack **stack, struct Data *data) { pthread_mutex_lock(&(data->mutex)); pthread_cancel((*stack)->thread); pop(&*stack); data->count--; pthread_mutex_unlock(&(data->mutex)); } void closeAllThreads(struct Stack **stack, struct Data *data) { pthread_mutex_lock(&(data->mutex)); while(size(*stack) != 0) { pthread_cancel((*stack)->thread); pop(stack); data->count--; } pthread_mutex_unlock(&(data->mutex));; } void createSignalObject(struct Data *data) { data->count = 0; pthread_mutex_init(&(data->mutex), 0); pthread_mutex_unlock(&(data->mutex)); } void closeSignalObject(struct Data *data) { pthread_mutex_destroy(&(data->mutex)); }
0
#include <pthread.h> int busy = 0; int waiting = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t OKtoread = PTHREAD_COND_INITIALIZER; pthread_cond_t OKtowrite = PTHREAD_COND_INITIALIZER; int readercount = 0; void readerStart(){ pthread_mutex_lock(&mutex); if (busy == 1){ pthread_cond_wait(&OKtoread,&mutex); } readercount = readercount + 1; pthread_cond_signal(&OKtoread); pthread_mutex_unlock(&mutex); } void readerEnd(){ pthread_mutex_lock(&mutex); readercount = readercount - 1; if (busy == 1){ pthread_cond_signal(&OKtowrite); } pthread_mutex_unlock(&mutex); } void writerStart(){ pthread_mutex_lock(&mutex); waiting = waiting + 1; if (busy == 1 || readercount != 0){ pthread_cond_wait(&OKtowrite,&mutex); } busy = 1; waiting = waiting - 1; pthread_mutex_unlock(&mutex); } void writerEnd(){ pthread_mutex_lock(&mutex); busy = 0; if (waiting > 0){ pthread_cond_signal(&OKtoread); }else{ pthread_cond_signal(&OKtowrite); } pthread_mutex_unlock(&mutex); } int main() { printf("ende"); return 0; }
1
#include <pthread.h> char *pbs_geterrmsg( int connect) { char *errmsg; if ((connect < 0) || (connect > PBS_NET_MAX_CONNECTIONS)) { return(0); } pthread_mutex_lock(connection[connect].ch_mutex); errmsg = connection[connect].ch_errtxt; pthread_mutex_unlock(connection[connect].ch_mutex); return(errmsg); }
0
#include <pthread.h> int NUM_INT; int BUFFER_SIZE; int NUM_PROD; int NUM_CON; int counter = 0; int *buffer; int *pid; int *cid; int buf_index = -1; int ctotal = 0; int cnum; sem_t spaces; sem_t items; pthread_mutex_t prod_mutex; pthread_mutex_t con_mutex; pthread_mutex_t buffer_mutex; struct timeval tv; double t1; double t2; int produce(int pid) { return counter++; } void consume(int cid, int value, int ctotal) { int sqrt_value = sqrt((double)value); if (sqrt_value * sqrt_value == value) { printf("%d %d %d\\n", cid, value, sqrt_value); } } void *producer(void *arg) { int *pid = (int *)arg; while (1) { pthread_mutex_lock(&prod_mutex); if (counter == NUM_INT) { pthread_mutex_unlock(&prod_mutex); break; } else if (counter % NUM_PROD == *pid) { int v = produce(*pid); pthread_mutex_unlock(&prod_mutex); sem_wait(&spaces); pthread_mutex_lock(&buffer_mutex); buffer[++buf_index] = v; pthread_mutex_unlock(&buffer_mutex); sem_post(&items); } else { pthread_mutex_unlock(&prod_mutex); } } pthread_exit(0); } void *consumer(void *arg) { int *cid = (int *)arg; while (1) { pthread_mutex_lock(&con_mutex); if (NUM_INT - ctotal < cnum) { cnum--; pthread_mutex_unlock(&con_mutex); break; } pthread_mutex_unlock(&con_mutex); sem_wait(&items); pthread_mutex_lock(&buffer_mutex); int temp = buffer[buf_index]; buffer[buf_index--] = -1; ctotal++; pthread_mutex_unlock(&buffer_mutex); sem_post(&spaces); consume(*cid, temp, ctotal); } pthread_exit(0); } int main(int argc, char **argv) { if (argc != 5) { printf("Error! Wrong number of arguments.\\n"); return -1; } NUM_INT = atoi(argv[1]); BUFFER_SIZE = atoi(argv[2]); NUM_PROD = atoi(argv[3]); NUM_CON = cnum = atoi(argv[4]); if (NUM_INT <= 0 || BUFFER_SIZE <= 0 || NUM_PROD <= 0 || NUM_CON <= 0) { printf("Error! Invalid arguments.\\nN: %d, B: %d, P: %d, C: %d.\\n", NUM_INT, BUFFER_SIZE, NUM_PROD, NUM_CON); return -1; } counter = 0; buffer = malloc(BUFFER_SIZE * sizeof(int)); int i, j, k; for (i = 0; i < BUFFER_SIZE; i++) { buffer[i] = -1; } sem_init(&spaces, 0, BUFFER_SIZE); sem_init(&items, 0, 0); pthread_mutex_init(&prod_mutex, 0); pthread_mutex_init(&con_mutex, 0); pthread_mutex_init(&buffer_mutex, 0); pid = malloc(NUM_PROD * sizeof(int)); cid = malloc(NUM_CON * sizeof(int)); pthread_t prod[NUM_PROD]; pthread_t con[NUM_CON]; gettimeofday(&tv, 0); t1 = tv.tv_sec + tv.tv_usec / 1000000.0; for (j = 0; j < NUM_PROD; j++) { pid[j] = j; pthread_create(&prod[j], 0, producer, &pid[j]); } for (k = 0; k < NUM_CON; k++) { cid[k] = k; pthread_create(&con[k], 0, consumer, &cid[k]); } for (j = 0; j < NUM_PROD; j++) { pthread_join(prod[j], 0); } for (k = 0; k < NUM_CON; k++) { pthread_join(con[k], 0); } gettimeofday(&tv, 0); t2 = tv.tv_sec + tv.tv_usec / 1000000.0; printf("System execution time: %.6lf seconds\\n", t2 - t1); free(buffer); free(pid); free(cid); sem_destroy(&spaces); sem_destroy(&items); pthread_mutex_destroy(&prod_mutex); pthread_mutex_destroy(&con_mutex); pthread_mutex_destroy(&buffer_mutex); pthread_exit(0); }
1
#include <pthread.h> void *createplane(void *args); void startlanding (int pno, int rno); int pno; int arrived; pthread_t tid; int fcap; int emeflag; int p; int landflag; }plane; int number; int occupied; }runwayst; pthread_mutex_t runway; pthread_mutex_t runway2; pthread_mutex_t runway3; pthread_mutex_t planes; pthread_mutex_t aplanes; plane allplanes[25]; runwayst runways[3]; int em_count; int main (int argc, char* argv) { int tstatus; srand(time(0)); int i; for( i = 0; i < 3 ; i++) { runways[i].number = i; runways[i].occupied = 0; } for (i = 0; i < 25; i++) { allplanes[i].pno = i + 1; allplanes[i].fcap = (rand() % (150 - 10)) + 10; allplanes[i].landflag = 0; allplanes[i].arrived = 0; allplanes[i].emeflag = 0; allplanes[i].p = 0; } if ( (pthread_mutex_init (&runway, 0)) != 0) { printf("\\n Error creating semaphore\\n"); exit(1); } if ((pthread_mutex_init (&runway2, 0)) != 0) { printf("\\n Error creating semaphore\\n"); exit(1); } if ((pthread_mutex_init (&runway3, 0)) != 0) { printf("\\n Error creating semaphore\\n"); exit(1); } if ((pthread_mutex_init (&planes, 0)) != 0) { printf("\\n Error creating semaphore\\n"); exit(1); } if ((pthread_mutex_init (&aplanes, 0)) != 0) { printf("\\n Error creating semaphore\\n"); exit(1); } for (i = 0 ; i < 25; i ++) { tstatus = pthread_create (&allplanes[i].tid, 0, createplane, (void *) &allplanes[i]); if(tstatus != 0) { printf("Error while creating a thread\\n"); exit(1); } sleep((rand()%5)); } for ( i = 0; i < 25; i++) { pthread_join(allplanes[i].tid, 0); } pthread_mutex_destroy(&runway); pthread_mutex_destroy(&runway2); pthread_mutex_destroy(&runway3); pthread_mutex_destroy(&planes); pthread_mutex_destroy(&aplanes); return 0; } void startlanding (int pno, int rno) { allplanes[pno].landflag = 1; if(allplanes[pno].emeflag == 1) { printf("Plane %d with emergency status is starting to land in runway %d with fuel %d left \\n", pno, rno, allplanes[pno].fcap); int ltime = (rand() % 5)+1; if(ltime> allplanes[pno].fcap) { printf("Plane %d with emergency status cannot land, hence aborting, run for safety\\n", pno); exit(0); } sleep(ltime); printf("Plane %d with emergency status has landed on the runway %d with fuel %d remaining\\n", pno, rno, allplanes[pno].fcap - ltime); int cltime = (rand() % 5) + 1; sleep(cltime); printf("Plane %d with emergency status has cleared the runway %d\\n", pno, rno); pthread_mutex_lock(&planes); em_count--; pthread_mutex_unlock(&planes); } else { printf("Plane %d is about to land at runway %d to land with fuel %d\\n", pno, rno, allplanes[pno].fcap); int ltime = rand()%8 + 1; if(ltime > allplanes[pno].fcap) { printf("Plane %d cannot land, crashing!!!!! run!!", pno); exit(0); } sleep(ltime); printf("Plane %d has landed on the runway %d with fuel %d remaining\\n", pno, rno, allplanes[pno].fcap - ltime); int cltime = rand() % 10 + 3; sleep(cltime); printf("Plane %d cleared the runway %d\\n", pno, rno); } if(rno == 0) { pthread_mutex_lock(&runway); runways[rno].occupied = 0; pthread_mutex_unlock(&runway); } if(rno == 1) { pthread_mutex_lock(&runway2); runways[rno].occupied = 0; pthread_mutex_unlock(&runway2); } if(rno == 2) { pthread_mutex_lock(&runway3); runways[rno].occupied = 0; pthread_mutex_unlock(&runway3); } } void *createplane(void *args) { long planetid; int flag = 0; int pno = ((plane *)args)->pno ; printf("Plane %d has arrived in the airzone with fuel %d\\n", pno, allplanes[pno].fcap); allplanes[pno].arrived = 1; int b = 0; int a = 0; plane tempplane; tempplane.emeflag = 0; tempplane.fcap = 100000; tempplane.landflag = 0; tempplane.arrived = 1; for( a = 0; a < 25; a++ ) { if( ((tempplane.fcap > allplanes[a].fcap) && (allplanes[a].landflag==0)) && (allplanes[a].arrived==1) ) { tempplane = allplanes[a]; b = a; } } allplanes[b].p = 1; int i; int cflag = 0; while( allplanes[pno].fcap > 1) { for(i=0; i < allplanes[pno].fcap; i++) { if((em_count > 0 && allplanes[pno].emeflag == 0) || (allplanes[pno].p!=1)) { allplanes[pno].fcap--; sleep(1); } else { if(runways[0].occupied == 0) { pthread_mutex_lock(&runway); runways[0].occupied = 1; pthread_mutex_unlock(&runway); startlanding(pno, 0); flag = 1; return; } else if(runways[1].occupied == 0) { pthread_mutex_lock(&runway2); runways[1].occupied = 1; pthread_mutex_unlock(&runway2); startlanding(pno, 1); flag = 1; return; } else if(runways[2].occupied == 0) { pthread_mutex_lock(&runway3); runways[2].occupied = 1; pthread_mutex_unlock(&runway3); startlanding(pno, 2); flag = 1; return; } else { sleep(1); allplanes[pno].fcap--; } } if((cflag==0) && (allplanes[pno].fcap < 10)) { printf("Plane %d has reached its danger zone with less fuel\\n", pno); cflag = 1; } if(rand()%22 == 3) { printf("Plane %d is now in an emergency state \\n", pno); pthread_mutex_lock(&planes); em_count++; pthread_mutex_unlock(&planes); allplanes[pno].p = 1; } } } if(flag == 0) { printf("Plane %d crashed causing the airport to blast, please run for safety\\n", pno); exit(0); } }
0
#include <pthread.h> int main() { pthread_mutex_t mutex; int rc; if((rc=pthread_mutex_init(&mutex,0)) != 0) { fprintf(stderr,"Error at pthread_mutex_init(), rc=%d\\n",rc); return PTS_UNRESOLVED; } if((rc=pthread_mutex_lock(&mutex)) == 0) { pthread_mutex_unlock(&mutex); printf("Test PASSED\\n"); return PTS_PASS; } else if(rc == EINVAL) { fprintf(stderr,"Invalid mutex object\\n"); return PTS_UNRESOLVED; } else if(rc == EAGAIN) { fprintf(stderr,"The maximum number of recursive locks has been exceeded\\n"); return PTS_UNRESOLVED; } else if(rc == EDEADLK) { fprintf(stderr,"The current thread already owns the mutex\\n"); return PTS_UNRESOLVED; } else { printf("Test FAILED\\n"); return PTS_FAIL; } }
1
#include <pthread.h> int mediafirefs_chown(const char *path, uid_t uid, gid_t gid) { printf("FUNCTION: chown. path: %s\\n", path); (void)path; (void)uid; (void)gid; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "chown not implemented\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOSYS; }
0
#include <pthread.h> void sig_catch(int sig); void barber(void *); void customer(void *); void get_hair_cut(void); void cut_hair(void); void line_pop(void); void line_push(void); struct chair { struct chair *next; }; struct line { int number_of_customers; int chairs; struct chair *current; struct chair *next; }; pthread_mutex_t barber_lock; pthread_mutex_t add_lock; struct line global_queue; void sig_catch(int sig){ printf("Catching signal %d\\n", sig); kill(0,sig); exit(0); } void line_push(void) { struct chair new; struct chair *ref = global_queue.current; if(global_queue.number_of_customers >= global_queue.chairs) { return; } new.next = 0; while(global_queue.next != 0) { ref = ref->next; } ref->next = &new; global_queue.number_of_customers++; } void line_pop(void) { struct chair *ref = global_queue.current; global_queue.number_of_customers--; global_queue.current = global_queue.next; if(global_queue.next != 0) { global_queue.next = global_queue.current->next; } ref = 0; } void barber(void *queue) { int i; int copy_of_customer_number; for(;;) { i = 0; copy_of_customer_number = global_queue.number_of_customers; while(global_queue.number_of_customers == 0) { printf("The Barber is sleeping\\n"); sleep(5); } for(i = 0; i < copy_of_customer_number; i++) { cut_hair(); } } } void customer(void *queue) { if(global_queue.number_of_customers >= global_queue.chairs) { printf("Line is full. Leaving\\n"); return; } pthread_mutex_lock(&add_lock); line_push(); pthread_mutex_unlock(&add_lock); printf("In chair waiting\\n"); pthread_mutex_lock(&barber_lock); get_hair_cut(); line_pop(); pthread_mutex_unlock(&barber_lock); } void cut_hair(void) { printf("Cutting hair\\n"); sleep(10); printf("Done cutting hair\\n"); } void get_hair_cut(void) { printf("Getting hair cut\\n"); sleep(10); printf("Done getting hair cut\\n"); } int main(int argc, char **argv) { pthread_t barber_thread; pthread_t c1, c2, c3, c4; void *barber_func = barber; void *customer_func = customer; struct chair one; struct sigaction sig; sig.sa_flags = 0; sig.sa_handler = sig_catch; sigaction(SIGINT, &sig, 0); one.next = 0; global_queue.current = &one; pthread_mutex_init(&barber_lock, 0); pthread_mutex_init(&add_lock, 0); global_queue.chairs = 3; global_queue.number_of_customers = 0; pthread_create(&barber_thread, 0, barber_func, 0); sleep(5); pthread_create(&c1, 0, customer_func, 0); pthread_create(&c2, 0, customer_func, 0); pthread_create(&c3, 0, customer_func, 0); pthread_create(&c4, 0, customer_func, 0); for(;;) { } }
1
#include <pthread.h> int sharedByteRead = 0; int sharedTotalCount = 0; FILE *fp; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; { int thread_no; } tname; int string_search(char *data, int length, char *target) { int i; int found = 0; for (i = 0; i < length - strlen(target); i++) { found++; } return found; } void *GetDataBytes(void *param) { tname *name; name = (tname *) param; char data[1000]; int count; while (fread(data, sizeof(char), 1000, fp) == 1000) { pthread_mutex_lock(&mutex); sharedByteRead += 1000; pthread_mutex_unlock(&mutex); } printf("%d \\n",count ); pthread_mutex_lock(&mutex2); sharedTotalCount += count; pthread_mutex_unlock(&mutex2); pthread_exit(0); } int main(int argc, char **argv) { if (argc < 2) { printf("Please pass an input fp.\\n %d",argc); return 0; } fp = fopen(argv[1], "r"); if (!fp) { printf("Could not open %s for reading.\\n", argv[1]); return 0; } fseek(fp, 0L, 2); unsigned total_bytes = ftell(fp) * 8; fseek(fp, 0L, 0); pthread_t thread1, thread2, thread3, thread4; tname t1, t2, t3, t4; t1.thread_no = 1; t2.thread_no = 2; t3.thread_no = 3; t4.thread_no = 4; void *ret = 0; pthread_create(&thread1, 0, GetDataBytes, (void *) &t1); pthread_create(&thread2, 0, GetDataBytes, (void *) &t2); pthread_create(&thread3, 0, GetDataBytes, (void *) &t3); pthread_create(&thread4, 0, GetDataBytes, (void *) &t4); pthread_join(thread1, &ret); pthread_join(thread2, &ret); pthread_join(thread3, &ret); pthread_join(thread4, &ret); printf("Total count: %d\\n", sharedTotalCount); }
0
#include <pthread.h> struct List *list = 0; pthread_mutex_t stdoutLock; void lockstdout (void) { pthread_mutex_lock(&stdoutLock); } void unlockstdout (void) { pthread_mutex_unlock(&stdoutLock); } void printMsg (int id, char *msg) { lockstdout(); printf("Thread %d: %s\\n",id,msg); unlockstdout(); } void * threadfunc (void *dat) { int i,op,id,value; id = (int) dat; for (i = 0; i < 15; ++i) { op = rand() % 4; if (op == 0) { printMsg(id,"Insert To Front"); Insert(list, i); } else if (op == 1) { printMsg(id,"Append To End"); Append(list, i); } else if (op == 2) { printMsg(id,"Remove From Front"); RemoveFromStart(list); } else if (op == 3) { printMsg(id,"Remove From End"); RemoveFromEnd(list); } printMsg(id,"After Op: "); lockstdout(); StartIteration(list); while (GetValueAtIter(list,&value) == 1) { printf("%d ", value); } EndIteration(list); printf("\\n"); unlockstdout(); usleep((rand() % 20) * 1000); } printMsg(id,"Thread complete"); return 0; } int main (void) { int i; pthread_t threads[8]; srand(time(0)); pthread_mutex_init(&stdoutLock, 0); list = CreateList(); for (i = 0; i < 8; ++i) { pthread_create(&threads[i], 0, threadfunc, (void*) i); } for (i = 0; i < 8; ++i) { pthread_join(threads[i], 0); } DeleteList(list); list = 0; pthread_mutex_destroy(&stdoutLock); printf("MemUsed: %d\\n",GetMemUsed()); return 0; }
1
#include <pthread.h> int parse_data(char *data, char u_name[], char password[]) { char *p; p=strchr(data, '='); if(p == 0) return -1; strncpy(u_name, data, p-data); u_name[p-data]='\\0'; strcpy(password, p+1); return 0; } int user_reg(int connfd, char *data) { FILE *f; char *p; char buf[1024]; char u_name[50], name[50]; char password[50]; parse_data(data, u_name, password); pthread_mutex_lock(&database_mutex); f = fopen(DataBasePath, "r+"); if(f==0){ perror("fail to open"); return 1; } while(fgets(buf, 1024,f)!=0){ p=strchr(buf, '='); if(p == 0) return -1; *p = '\\0'; strcpy(name, buf); if(strcmp(u_name, name)==0){ return -1; } } strcat(data,"\\n"); fseek(f,0,2); fwrite(data,sizeof(char),strlen(data),f); fclose(f); sync(); pthread_mutex_unlock(&database_mutex); close(connfd); return 0; }
0
#include <pthread.h> char *head, *tail; pthread_cond_t cond; pthread_mutex_t m; volatile int le_lock; void *probably_malloc(long n) { void *x = mmap(0, n, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, 0 , 0); if (x == MAP_FAILED) { fprintf(stderr, "mmap failed %ld %d %d\\n", n, x, errno); exit(1); } return x; } void probably_free(void *x) { int ret = munmap(x, 4088 +8); if (ret == -1) { fprintf(stderr, "munmap failed %p %d\\n", x, errno); exit(1); } return; } void *writer(void *ignored) { long dick; char *next_head; pthread_mutex_lock(&m); while(1) { while((dick = ((long *) head)[0]) != 0) { if (dick < 0) { write(STDOUT_FILENO, head + 8, dick + 4088); exit(0); } write(STDOUT_FILENO, head + 8, 4088); next_head = ((char **) head)[0]; probably_free(head); head = next_head; } if (OSAtomicCompareAndSwapInt(0, 1, &le_lock)) { pthread_cond_wait(&cond, &m); le_lock = 0; } } } int fake_read(int fd, char *buf, long n) { long desired = n; long dick; while(1) { dick = read(fd, buf, desired); if (dick == desired) return n; if (dick < 0) return -1; if (dick == 0) return (n - desired); desired -= dick; buf += dick; } } int main(int argc, char **argv) { int fd_in = STDIN_FILENO; if (argc > 1) { fd_in = open(argv[1], O_RDONLY); if(fd_in == -1) { fprintf(stderr, "Oh dear, failed to open file %s %d.\\n", argv[1], fd_in); exit(1); } } pthread_cond_init(&cond, 0); pthread_mutex_init(&m, 0); le_lock = 0; char *x = probably_malloc(4088 + 8); ((void **) x)[0] = 0; head = x; tail = x; pthread_t the_writer; pthread_create(&the_writer, 0, writer, 0); int num_read; int cock; while(1) { num_read = fake_read(fd_in, tail + 8, 4088); if (num_read < 0) { fprintf(stderr, "Oh fuck, a read error %d\\n", num_read); exit(1); } if (num_read < 4088) { ((long *) tail)[0] = num_read - 4088; cock = OSAtomicCompareAndSwapInt(0, 1, &le_lock); pthread_cond_signal(&cond); if (!cock) { pthread_mutex_lock(&m); pthread_mutex_unlock(&m); pthread_cond_signal(&cond); } pthread_join(the_writer, 0); } x = probably_malloc(4088 + 8); ((long *) x)[0] = 0; ((char **) tail)[0] = x; pthread_cond_signal(&cond); tail = x; } }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static size_t i_gloabl_n = 0; void *thr_demo(void *args) { printf("this is thr_demo thread, pid: %d, tid: %lu\\n", getpid(), pthread_self()); pthread_mutex_lock(&mutex); int i; int *pa = (int *)args; size_t tid = pthread_self(); setbuf(stdout, 0); for (i = 0; i < 10; ++i) { printf("(tid: %lu):%lu:%d\\n", tid, ++i_gloabl_n, ++pa[0]); } return (void *)0; } void *thr_demo2(void *args) { printf("this is thr_demo2 thread, pid: %d, tid: %lu\\n", getpid(), pthread_self()); pthread_mutex_lock(&mutex); int i; int max = *(int *)args; int *pa = (int *)args; size_t tid = pthread_self(); setbuf(stdout, 0); for (i = 0; i < 20; ++i) { printf("(tid: %lu):%lu:%d\\n", tid, ++i_gloabl_n, ++pa[0]); } return (void *)10; } int main() { pthread_t pt1, pt2; int arg = 20; int ret; int *heap = (int *)malloc(sizeof(int)); assert(heap != 0); ret = pthread_create(&pt1, 0, thr_demo, heap); if (ret != 0) { do { perror("pthread_create"); exit(-1); } while(0); } ret = pthread_create(&pt2, 0, thr_demo2, heap); if (ret != 0) { do { perror("pthread_create"); exit(-1); } while(0); } printf("this is main thread, pid = %d, tid = %lu\\n", getpid(), pthread_self()); ret = pthread_join(pt1, (void *)&arg); if (ret != 0) { do { perror("pthread_join"); exit(-1); } while(0); } printf("arg = %d\\n", arg); pthread_mutex_unlock(&mutex); ret = pthread_join(pt2, (void *)&arg); if (ret != 0) { do { perror("pthread_join"); exit(-1); } while(0); } printf("arg = %d\\n", arg); pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); free(heap); return 0; }
0
#include <pthread.h> static pthread_mutex_t gtw_next_lock; static void * worker_function(void *thread_data) { (void)thread_data; while (1) { void* run_data; pthread_mutex_lock(&gtw_next_lock); run_data = gtw_next(); pthread_mutex_unlock(&gtw_next_lock); if (run_data == 0) { break; } else { gtw_run(run_data); } } pthread_exit(0); } int main(int argc, char ** argv) { int x; int worker_count = gtw_prepare(argc, argv); pthread_t workers[worker_count]; pthread_mutex_init(&gtw_next_lock, 0); for (x = 0; x < worker_count; x++) { pthread_create(&workers[x], 0, &worker_function, 0); } for (x = 0; x < worker_count; x++) { pthread_join(workers[x], 0); } pthread_mutex_destroy(&gtw_next_lock); return 0; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void* thr_fn(void* arg) { int err,signo; sigset_t peing; printf("thr_fn sleep(10) to ready pengingset\\n"); sleep(10); for(;;){ err = sigwait(&mask,&signo); if(err != 0) err_exit(err,"sigwait failed"); switch(signo){ case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return 0; default: printf("unexpected signal %d\\n",signo); } } } void sig_quit(int signo){ printf("catcht SIGQUIT \\n"); } int main(void){ int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask,SIGINT); sigaddset(&mask,SIGQUIT); if((err=pthread_sigmask(SIG_BLOCK,&mask,&oldmask)) != 0) err_quit(err,"SIG_BLOCK error"); err = pthread_create(&tid,0,thr_fn,0); if(err != 0) err_quit(err,"can't create error"); pthread_mutex_lock(&lock); while(quitflag == 0) pthread_cond_wait(&wait,&lock); pthread_mutex_unlock(&lock); quitflag = 0; printf("sleep(5)....\\n"); signal(SIGQUIT,sig_quit); sleep(5); if(sigprocmask(SIG_SETMASK,&oldmask,0)<0) err_sys("SIG_SETMASK err"); exit(0); }
0
#include <pthread.h> int source[7]; int minBound[2]; int maxBound[2]; int channel[2]; int th_id = 0; pthread_mutex_t mid; pthread_mutex_t ms[2]; int findmin (int x, int y) { int idx = -1; int val = source[x]; for (int i = x+1; i < y; i++) { if (val > source[i]) { idx = i; val = source[i]; } } __VERIFIER_assert (idx >= x); __VERIFIER_assert (idx < y); return idx; } int findmin_channel () { int idx = 0; int val = channel[idx]; for (int i = 1; i < 2; i++) { if (val > channel[i]) { idx = i; val = source[i]; } } __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 2); return idx; } void *sort_thread (void * arg) { int id = -1; pthread_mutex_lock (&mid); id = th_id; th_id++; pthread_mutex_unlock (&mid); __VERIFIER_assert (id >= 0); int min, max = -1; pthread_mutex_lock (&ms[id]); min = minBound[id]; max = maxBound[id]; pthread_mutex_unlock (&ms[id]); __VERIFIER_assert (min >= 0); __VERIFIER_assert (min <= max); int _val = 0; while (min < max) { pthread_mutex_lock (&ms[id]); _val = channel[id]; pthread_mutex_unlock (&ms[id]); } return 0; } int main () { pthread_t ths[2]; pthread_mutex_init (&mid, 0); __libc_init_poet (); unsigned seed = (unsigned) time(0); srand (seed); printf ("Using seed %u\\n", seed); int i; for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int (0, 20); printf ("source[%d] = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } printf ("==============\\n"); int j = 0; int delta = 7/2; for (i = 0; i < 2; i++) { channel[i] = 0; minBound[i] = j; maxBound[i] = j+delta; j+=delta+1; pthread_mutex_init (&ms[i], 0); pthread_create (&ths[i], 0, sort_thread, 0); } for (i = 0; i < 7; i++) { for (j = 0; j < 2; j++) { } } for (i = 0; i < 2; i++) { pthread_join (ths[i], 0); } return 0; }
1
#include <pthread.h> int state[5]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutexattr_t attr; void think(int i); void take_forks(int i); void eat(int i); void put_forKs(int i); int test(int i); void *philosopher(void *i); void *philosopher(void *i) { int *num=(int *)i; think(*num); take_forks(*num); eat(*num); put_forks(*num); } void take_forks(int i) { pthread_mutex_lock(&mutex); test(i); pthread_mutex_unlock(&mutex); return ; } void put_forks(int i) { state[i]=0; } int test(int i) { if(state[(i-1+5)%5]!=1 && state[(i+1)%5]!=1); { state[i]=1; return 1; } return 0; } void eat(int i) { if(state[i]==1) { printf("philosopher %d is eating......\\n",i); sleep(2); } } void think(int i) { if(state[i]==0) { printf("philosopher %d is thinking......\\n",i); sleep(2); } } int main() { int i=0; pthread_t id[5];int ret; printf("testing ....\\n"); while(1) { for(i=0;i<5;i++) { ret=pthread_create(&id[i],0,philosopher,(void *)&i); printf("ret = %d\\n",ret); if(ret<0) { printf("create pthread error !\\n"); return 1; } pthread_join(id[i],0); } } }
0
#include <pthread.h> func_malloc _origin_malloc; func_free _origin_free; pthread_mutex_t lock_foot; void* origin_malloc(size_t size) { assert(_origin_malloc); return _origin_malloc(size); } void origin_free(void *ptr) { assert(_origin_free); return _origin_free(ptr); } int isFootInit = 0; void foot_init() { pthread_mutex_lock(&lock_foot); if (!isFootInit) { printf("[+] foot init\\n"); char *msg = 0; if (_origin_malloc == 0) { char fname[] = "malloc"; _origin_malloc = dlsym(RTLD_NEXT, fname); printf("old_%s = 0x%px\\n", fname, _origin_malloc); if ((_origin_malloc == 0) || ((msg = dlerror()) != 0)) { printf("dlsym [%s] failed : %s\\n", fname, msg); goto clean; } else { printf("dlsym: wrapping [%s] done\\n", fname); } } if (_origin_free == 0) { char fname[] = "free"; _origin_free = dlsym(RTLD_NEXT, fname); printf("old_%s = 0x%px\\n", fname, _origin_free); if ((_origin_free == 0) || ((msg = dlerror()) != 0)) { printf("dlsym [%s] failed : %s\\n", fname, msg); goto clean; } else { printf("dlsym: wrapping [%s] done\\n", fname); } } isFootInit = 1; } clean: pthread_mutex_unlock(&lock_foot); } static void __foot_init(void) { }
1
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *ptr; void *thread1() { printf ("thread1 : I'm thread 1\\n"); void *aa = malloc(128); free(ptr); for (i = 0; i < 10; i++) { printf("thread1 : number = %d\\n",number); printf("aa ptr %p.\\n", aa); void *bb = malloc(128); printf("bb ptr %p.\\n", bb); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); free(aa); sleep(1); } printf("thread1 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void *thread2() { printf("thread2 : I'm thread 2\\n"); for (i = 0; i < 10; i++) { printf("thread2 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(1); } printf("thread2 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int temp; ptr = malloc(128); printf("ptr %p.\\n", ptr); memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0) printf("线程1创建失败!\\n"); else printf("线程1被创建\\n"); if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0) printf("线程2创建失败"); else printf("线程2被创建\\n"); } void thread_wait(void) { printf("==================thread_wait start=================\\n"); if(thread[0] !=0) { pthread_join(thread[0],0); printf("线程1已经结束\\n"); } if(thread[1] !=0) { pthread_join(thread[1],0); printf("线程2已经结束\\n"); } printf("=================thread_wait end==================\\n"); } int main(int argc, char *argv[]) { pthread_mutex_init(&mut,0); printf("我是主函数哦,我正在创建线程,呵呵\\n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\\n"); thread_wait(); return 0; }
0
#include <pthread.h> static struct hosts_info hosts_ = {{0, 0}, -1, 0, 0, ""}; static char *path_hosts_ = 0; static pthread_mutex_t hosts_mutex_ = PTHREAD_MUTEX_INITIALIZER; int hosts_file_modified_r(struct timespec *ts) { struct stat st; log_debug("checking if file \\"%s\\" was modified", path_hosts_); if (stat(path_hosts_, &st) == -1) { log_debug("stat on \\"%s\\" failed: \\"%s\\"", path_hosts_, strerror(errno)); return -1; } if (st.st_mtime == ts->tv_sec) return 0; log_debug("%s modified", path_hosts_); ts.tv_sec = st.st_mtime; return 1; } int hosts_read(struct hosts_ent **hent) { int e, n = 0, c; char buf[HOSTS_LINE_LENGTH + 1], *s; struct addrinfo hints, *res; struct hosts_ent *h; FILE *f; if ((f = fopen(path_hosts_, "r")) == 0) { log_debug("fopen(\\"%s\\"...) failed: \\"%s\\"", path_hosts_, strerror(errno)); return -1; } pthread_mutex_lock(&hosts_mutex_); if (*hent) { free(*hent); *hent = 0; } memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET6; hints.ai_flags = AI_NUMERICHOST; while (fgets(buf, HOSTS_LINE_LENGTH, f) != 0) { if ((s = strtok(buf, " \\t\\r\\n")) == 0) continue; continue; if ((e = getaddrinfo(s, 0, &hints, &res)) != 0) { log_debug("getaddrinfo(\\"%s\\"...) failed: \\"%s\\"", s, gai_strerror(e)); continue; } if (res->ai_family != AF_INET6) { log_debug("ai_family = %d (!= AF_INET6)", res->ai_family); freeaddrinfo(res); continue; } for (c = 0; (s = strtok(0, " \\t\\r\\n")); c++) { if ((strlen(s) > strlen(hosts_.hdom)) && !strcasecmp(s + (strlen(s) - strlen(hosts_.hdom)), hosts_.hdom)) { if ((*hent = realloc(*hent, ++n * sizeof(struct hosts_ent))) == 0) { log_msg(LOG_ERR, "realloc failed: \\"%s\\"", strerror(errno)); n--; break; } h = (*hent) + n - 1; h->addr = ((struct sockaddr_in6*) res->ai_addr)->sin6_addr; strlcpy(h->name, s, NI_MAXHOST); break; } } freeaddrinfo(res); } pthread_mutex_unlock(&hosts_mutex_); (void) fclose(f); log_debug("found %d valid IPv6 records in %s", n, path_hosts_); return n; } int hosts_check(void) { if (path_hosts_ == 0) { path_hosts_ = _PATH_HOSTS; } if (hosts_file_modified_r(&hosts_.hosts_ts)) hosts_.hosts_ent_cnt = hosts_read(&hosts_.hosts_ent); return 0; } int hosts_get_name(const struct in6_addr *addr, char *buf, int s) { int i; struct hosts_ent *h; log_debug("looking up name"); pthread_mutex_lock(&hosts_mutex_); for (i = hosts_.hosts_ent_cnt - 1, h = hosts_.hosts_ent; i >= 0; i--, h++) if (IN6_ARE_ADDR_EQUAL(addr, &h->addr)) { strlcpy(buf, h->name, s); log_debug("name \\"%s\\" found", buf); break; } pthread_mutex_unlock(&hosts_mutex_); if (i < 0) return -1; return 0; } void hosts_init(const char *dom) { hosts_.hdom = dom; }
1
#include <pthread.h> int g1, g2, g3; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; void *t1(void *arg) { pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); g1 = g2 + 1; pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); return 0; } void *t2(void *arg) { pthread_mutex_lock(&mutex2); pthread_mutex_lock(&mutex3); g2 = g3 - 1; pthread_mutex_unlock(&mutex3); pthread_mutex_unlock(&mutex2); return 0; } void *t3(void *arg) { pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex3); g3 = g1 + 1; pthread_mutex_unlock(&mutex3); pthread_mutex_unlock(&mutex1); return 0; } int main(void) { pthread_t id1, id2, id3; int i; for (i = 0; i < 1000000; i++) { pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_create(&id3, 0, t3, 0); pthread_join (id1, 0); pthread_join (id2, 0); pthread_join (id3, 0); printf("%d: g1 = %d, g2 = %d, g3 = %d.\\n", i, g1, g2, g3); } return 0; }
0
#include <pthread.h> long module_tick_ts_diff(struct timespec *ts_a, struct timespec *ts_b) { long nsec = (ts_a->tv_nsec - ts_b->tv_nsec); nsec += (ts_a->tv_sec - ts_b->tv_sec)*1000000000; return nsec; } void module_tick_master_upd_out(struct module_tick *list) { struct module_tick *ptr = list; while(ptr){ if(!ptr->inwait) ptr->outerr++; ptr = ptr->next; } } void module_tick_master_print_inwait(struct module_tick *list) { struct module_tick *ptr = list; int i = 0; while(ptr){ if(!ptr->inwait){ struct module_base *base = ptr->base; if(base) fprintf(stderr, "inwait %d '%s'\\n", i, base->name); else fprintf(stderr, "inwait %d \\n", i); } ptr = ptr->next; i++; } } int module_tick_master_loop(struct module_tick_master *master, int *run) { pthread_mutex_t mutex; pthread_cond_t cond; struct timespec ts_next; struct timespec ts_now; int dbglev = master->dbglev; long ns_diff = 0; unsigned long ns_interval = master->ms_interval*1000000; int sec_align = master->sec_align; unsigned long seq = 0; if(dbglev) fprintf(stderr, "start tick interval %lu ns\\n", ns_interval); pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); clock_gettime(CLOCK_REALTIME, &ts_next); ts_next.tv_nsec = 0; ts_next.tv_sec += 1; while(*run){ if(ts_next.tv_nsec >= 1000000000){ ts_next.tv_sec += 1; ts_next.tv_nsec -= 1000000000; } if(sec_align&&(ts_next.tv_nsec< ns_interval)) ts_next.tv_nsec = 0; pthread_cond_timedwait(&cond, &mutex, &ts_next); pthread_mutex_lock(&master->mutex); clock_gettime(CLOCK_REALTIME, &ts_now); master->seq = seq++; master->time.tv_sec = ts_next.tv_sec; master->time.tv_usec = ts_next.tv_nsec/1000; pthread_cond_broadcast(&master->cond); if(master->outcnt){ module_tick_master_upd_out(master->ticks); master->notinerr += master->outcnt; fprintf(stderr, "out count %d\\n", master->outcnt); module_tick_master_print_inwait(master->ticks); } pthread_mutex_unlock(&master->mutex); ns_diff = module_tick_ts_diff(&ts_now, &ts_next); if(ns_diff > 20000000){ master->lateerr++; if(ns_diff > ns_interval){ master->rollerr++; fprintf(stderr, "rollover\\n"); } } ts_next.tv_nsec += ns_interval; if(dbglev) fprintf(stderr, "tick %ld %ld %ld.%3.3ld\\n", seq-1, ns_diff/1000000, ts_now.tv_sec, ts_now.tv_nsec/1000000); } pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0; } int module_tick_master_init(struct module_tick_master *master, int ms_interval, int sec_align) { fprintf(stderr, "init tick master %p interval %d ms\\n", master, ms_interval); assert(master); memset(master , 0 , sizeof(*master)); master->run = 1; module_tick_master_set_interval(master, ms_interval); master->sec_align = sec_align; master->ticks = 0; pthread_cond_init(&master->cond, 0); pthread_mutex_init(&master->mutex, 0); fprintf(stderr, "tick master created %p\\n", master); return 0; } void module_tick_master_stop(struct module_tick_master *master) { void* retptr = 0; int retval = 0; fprintf(stderr, "stop tick master %p\\n", master); master->run = 0; retval = pthread_join(master->thread, &retptr); if(retval < 0) PRINT_ERR("pthread_join returned %d in tick master : %s", retval, strerror(-retval)); PRINT_DBG(1, "pthread joined"); pthread_cond_destroy(&master->cond); pthread_mutex_destroy(&master->mutex); }
1
#include <pthread.h> void *functionA(); void *functionB(); void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; main(){ pthread_t thread1, thread2, thread3; int rc1, rc2, rc3; printf("\\033[2J"); printf("\\033[%d;%dH", 0 ,0); printf("THREAD ONE\\n"); printf("===========================================================\\n"); printf("\\033[%d;%dH", 8, 0); printf("THREAD TWO\\n"); printf("===========================================================\\n"); printf("\\033[%d;%dH", 16, 0); printf("THREAD THREE\\n"); printf("===========================================================\\n"); if( rc1=pthread_create(&thread1, 0, &functionA, 0)){ printf("Error in creating thread %d\\n", rc1 ); } if( rc2=pthread_create(&thread2, 0, &functionB, 0)){ printf("Error in creating thread %d\\n", rc2 ); } if( rc3=pthread_create(&thread3, 0, &functionC, 0)){ printf("Error in creating thread %d\\n", rc3 ); } pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_join(thread3, 0); pthread_mutex_destroy(&mutex1); exit(0); } void *functionA(){ while(1){ pthread_mutex_lock(&mutex1); printf("\\033[%d;%dH", 4, 0); printf("I am a function 1111111111111111111111111111111111111\\n"); pthread_mutex_unlock(&mutex1); } pthread_exit(0); } void *functionB(){ while(1){ pthread_mutex_lock(&mutex1); printf("\\033[%d;%dH", 11, 0); printf("I am a function 2222222222222222222222222222222222222\\n"); pthread_mutex_unlock(&mutex1); } pthread_exit(0); } void *functionC(){ while(1){ pthread_mutex_lock(&mutex1); printf("\\033[%d;%dH", 19, 0); printf("I am a function 3333333333333333333333333333333333333\\n"); pthread_mutex_unlock(&mutex1); } pthread_exit(0); }
0
#include <pthread.h> pthread_t tid[2]; pthread_mutex_t lock; sem_t done_filling_list; sem_t filling_list; extern void Sim808_GPS_GSM_Module_Power(); extern int sendGPSData() ; extern int receiveGPSData() ; void* gpsDataReceiverTask(void *arg) { unsigned long i = 0; pthread_t id = pthread_self(); while(1) { sem_wait(&filling_list); pthread_mutex_lock(&lock); if(pthread_equal(id,tid[0])) { printf("\\n Receiver thread processing\\n"); restart: if(!receiveGPSData()) { printf("\\n ReceiveData Not OK, so resetting the module"); startRecoveryForReceiveDataFailed(0); goto restart; } } pthread_mutex_unlock(&lock); sem_post(&done_filling_list); } return 0; } void* gpsDataSenderTask(void *arg) { unsigned long i = 0; pthread_t id = pthread_self(); while(1) { sem_wait(&done_filling_list); pthread_mutex_lock(&lock); if(pthread_equal(id,tid[1])) { printf("\\n Sender thread processing\\n"); if(!sendGPSData()) { printf("\\n Send Data Not OK, so resetting the module"); startRecoveryForSendDataFailed(0); pthread_mutex_unlock(&lock); sem_post(&filling_list); } } pthread_mutex_unlock(&lock); sem_post(&filling_list); } } int SIM808_main() { int i,s = 0; int err,res; if(!openSIM808Port()) { printf("\\n Comport is not initialized\\n"); return 0; } if(!getSim808DeviceInfo()) { printf("Device is not initialized\\n"); return 0; } res = sem_init(&done_filling_list, 0 , 0); if (res < 0) { perror("Semaphore initialization failed"); exit(0); } if (sem_init(&filling_list, 0, 1)) { perror("Semaphore initialization failed"); exit(0); } if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } err = pthread_create(&(tid[0]), 0, &gpsDataReceiverTask, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); err = pthread_create(&(tid[1]), 0, &gpsDataSenderTask, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); while(1) { sleep(86400); sem_wait(&filling_list); sem_wait(&done_filling_list); printf("Canceling thread\\n"); s = pthread_cancel(tid[0]); s = pthread_cancel(tid[1]); sleep(60); system("reboot"); } return 0; }
1
#include <pthread.h> pthread_t atendentes [5]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; int filas_vazias=5; pthread_t gclientes; int clientes=50; int clientes_atendidos=0; int filas [5]; sem_t empty; sem_t full; void *gerenciar_clientes(void *thread_id){ int y=0; int aux=0; int x=0; int j; while((clientes_atendidos!=50)){ if(clientes>0){ usleep(rand() % 100); x= rand() % 2; if(x>=clientes){ x=clientes; } while(x!=0){ pthread_mutex_lock(&mutex); aux=filas[0]; y=0; for(j=1; j<5; j++){ if(filas[j]==0){ y=j; break; } if(filas[j]<=aux){ aux=filas[j]; y=j; } } pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if(filas[y]==0){ sem_wait(&empty); filas_vazias--; sem_post(&full); } pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); filas[y]++; pthread_mutex_unlock(&mutex); clientes--; x--; } } } } int *atendimento_cliente(void *thread_id){ int aux=0; int j=0; int y=0; while(1){ while((clientes>0) ||(filas[(int)thread_id]>0)){ usleep(rand() % 1000000); pthread_mutex_lock(&mutex); if(filas[(int)thread_id]==1){ sem_wait(&full); filas_vazias++; sem_post(&empty); } pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); filas[(int)thread_id]--; pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex3); clientes_atendidos++; pthread_mutex_unlock(&mutex3); printf("Fila %d, %d cliente na fila-%d clientes atendidos, e tem %d filas vazias\\n", (int)thread_id, filas[(int)thread_id], clientes_atendidos, filas_vazias); } if(clientes_atendidos==50){ break; } aux=0; y=5; pthread_mutex_lock(&mutex); for(j=0; j<5; j++){ if((((int)thread_id)!=j)&&(filas[j]>1)){ if((filas[j]>=aux)){ aux=filas[j]; y=j; } } } pthread_mutex_unlock(&mutex); if(y!=5){ pthread_mutex_lock(&mutex); filas[y]--; filas[(int)thread_id]=1; sem_wait(&empty); filas_vazias--; sem_post(&full); pthread_mutex_unlock(&mutex); }else{ break; } } pthread_exit(0); } int main(int argc, char *argv[]) { int t; srand( (unsigned)time(0) ); sem_init(&empty, 0, 5); sem_init(&full, 0, 0); pthread_create(&gclientes, 0, gerenciar_clientes, (void*)50); for (t = 0; t<5; t++){ filas[t]=0; if (pthread_create(&atendentes[t], 0, atendimento_cliente, (void*)t)) { printf("Erro criação fila %d\\n", t); } } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t max_mutex = PTHREAD_MUTEX_INITIALIZER; float max_temp = -1; void * registerTemperature(void *arg) { float temp = *((float*)arg); free(arg); pthread_mutex_lock(&max_mutex); if(temp > max_temp) { printf("Server: updating maximum temperature to %.2f°C\\n", temp); max_temp = temp; } pthread_mutex_unlock(&max_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t threadids[20]; int i; float *temp; for(i=0; i<20; i++) { temp = malloc(sizeof(float)); *temp = random() % 30; printf("Client: sending temperature %.2f°C\\n", *temp); pthread_create(&threadids[i], 0, registerTemperature, temp); } for(i=0; i<20; i++) { pthread_join(threadids[i], 0); } printf("\\nMaximum temperature: %.2f°C\\n", max_temp); pthread_exit(0); }
1
#include <pthread.h> int *array=0; int array_length=0; pthread_mutex_t* mutex_border=0; pthread_mutex_t global_sum_mutex; pthread_cond_t global_sum_cond; int *thread_ids=0; int num_threads=0; int thread_counter=0; int num_swaps=-1; int flag=1; void *handler (void *arg) { int left_border; int right_border; int local_num_swaps=0; int i,val; int thread_id=*(int *)arg; printf("thread %d is alive\\n",thread_id); left_border=array_length/num_threads*thread_id; if(thread_id==num_threads-1) { right_border=array_length; } else { right_border=array_length/num_threads*(thread_id+1); } while(flag) { if(left_border) { pthread_mutex_lock(&mutex_border[thread_id-1]); if(array[left_border-1]>array[left_border]) { val=array[left_border]; array[left_border]=array[left_border-1]; array[left_border-1]=val; local_num_swaps=1; } if(array[left_border]>array[left_border+1]) { val=array[left_border]; array[left_border]=array[left_border+1]; array[left_border+1]=val; local_num_swaps++; } pthread_mutex_unlock(&mutex_border[thread_id-1]); } else { if(array[0]>array[1]) { val=array[0]; array[0]=array[1]; array[1]=val; local_num_swaps=1; } } for(i=left_border+2;i<right_border-1;i++) { if(array[i-1]>array[i]) { val=array[i]; array[i]=array[i-1]; array[i-1]=val; local_num_swaps++; } } if(right_border==array_length) { if(array[array_length-2]>array[array_length-1]) { val=array[array_length-2]; array[array_length-2]=array[array_length-1]; array[array_length-1]=val; local_num_swaps++; } } else { pthread_mutex_lock(&mutex_border[thread_id]); if(array[right_border-2]>array[right_border-1]) { val=array[right_border-2]; array[right_border-2]=array[right_border-1]; array[right_border-1]=val; local_num_swaps++; } if(array[right_border-1]>array[right_border]) { val=array[right_border-1]; array[right_border-1]=array[right_border]; array[right_border]=val; local_num_swaps++; } pthread_mutex_unlock(&mutex_border[thread_id]); } pthread_mutex_lock(&global_sum_mutex); num_swaps+=local_num_swaps; printf("thread %d num swaps %d\\n",thread_id,local_num_swaps); thread_counter++; local_num_swaps=0; if(thread_counter==num_threads) { if(num_swaps==0) flag=0; printf("thread %d global num swaps %d\\n",thread_id,num_swaps); num_swaps=0; thread_counter=0; pthread_cond_broadcast(&global_sum_cond); } else pthread_cond_wait(&global_sum_cond,&global_sum_mutex); pthread_mutex_unlock(&global_sum_mutex); } return 0; } int main(int argc,char **argv) { int i; pthread_t* threads=0; if(argc<3) { printf("Arguments are: sorter num_threads file\\n"); return 1; } num_threads=atoi(argv[1]); threads=(pthread_t *)malloc(num_threads*sizeof(pthread_t)); thread_ids=(int *)malloc(num_threads*sizeof(int)); mutex_border=(pthread_mutex_t *)malloc((num_threads-1)*sizeof(pthread_mutex_t)); if(read_array(&array,&array_length,argv[2])) { fprintf(stderr,"Can't read array from file '%s'\\n",argv[2]); return -1; } for(i=0;i<num_threads;i++) { thread_ids[i]=i; } for(i=0;i<num_threads-1;i++) { pthread_mutex_init(&mutex_border[i],0); } pthread_mutex_init(&global_sum_mutex,0); pthread_cond_init(&global_sum_cond,0); for(i=0;i<num_threads;i++) { if(pthread_create(&threads[i],0,handler,&thread_ids[i])) { perror("Can't create thread\\n"); return -1; } } for(i=0;i<num_threads;i++) { pthread_join(threads[i],0); } free(threads); free(thread_ids); for(i=0;i<num_threads-1;i++) { pthread_mutex_destroy(&mutex_border[i]); } pthread_mutex_destroy(&global_sum_mutex); pthread_cond_destroy(&global_sum_cond); for(i=0;i<array_length;i++) { printf("array[%d]=%d\\n",i,array[i]); } free(array); return 0; }
0
#include <pthread.h> int count=0; int flag=0; pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t CV = PTHREAD_COND_INITIALIZER; void helloW(int id) { pthread_mutex_lock(&lock1); if(id%2!=0) { while(count<10/2) { printf("%d Waiting...\\n",id); pthread_cond_wait(&CV,&lock1); } } count++; printf("Count:%d,Id: %d :Hello World\\n",count,id); if(count>=10/2 && flag==0) { pthread_cond_broadcast(&CV); flag=1; } pthread_mutex_unlock(&lock1); pthread_exit(0); } void main() { int n=10,i,err; pthread_t thread[n]; for(i=0;i<n;i++) { err=pthread_create(&thread[i], 0, helloW, i); if(err!=0) printf("\\nError Creating Thread:%d !!,%d\\n",i,errno); } for(i=0;i<n;i++) pthread_join(thread[i], 0); }
1
#include <pthread.h> pswd_t pswd; char * hash; } task_t; task_t * tasks[(16)]; int tail; int head; pthread_mutex_t tail_mutex; pthread_mutex_t head_mutex; sem_t full_sem; sem_t empty_sem; } queue_t; void queue_init (queue_t * queue) { queue->tail = 0; queue->head = 0; sem_init (&(queue->full_sem),0,sizeof (queue->tasks)/sizeof (queue->tasks[0])); sem_init (&(queue->empty_sem),0,0); pthread_mutex_init (&(queue->tail_mutex), 0); pthread_mutex_init (&(queue->head_mutex), 0); } void queue_push (queue_t * queue, task_t * task) { sem_wait (&(queue-> full_sem)); pthread_mutex_lock (&(queue-> tail_mutex)); queue-> tasks[queue-> tail] = task; queue-> tail++; if (queue-> tail == sizeof (queue-> tasks)/sizeof (queue-> tasks[0])) { queue-> tail=0; } pthread_mutex_unlock (&(queue-> tail_mutex)); sem_post (&(queue-> empty_sem)); } task_t * queue_pop (queue_t * queue) { task_t * task; sem_wait (&(queue-> empty_sem)); pthread_mutex_lock (&(queue-> head_mutex)); task = queue-> tasks[queue-> head]; queue-> head++; if (queue-> head == sizeof (queue-> tasks)/sizeof (queue-> tasks[0])) { queue->head = 0; } pthread_mutex_unlock (&(queue-> head_mutex)); sem_post (&(queue-> full_sem)); return task; } void * worker (void * arg){ int * i = arg; printf ("%d\\n", *i); return 0; } int main (int argc, char *argv[]) { int i; int ncpu = 2 + (long)sysconf (_SC_NPROCESSORS_ONLN); pthread_t ids[ncpu]; printf ("ncpu = %d\\n", ncpu); for (i = 0; i < ncpu; ++i) { pthread_create (&ids[i], 0, worker, &i); } for (i = 0; i < ncpu; ++i) pthread_join (ids[i], 0); return 0; }
0
#include <pthread.h> enum direction { north = 0, west = 1, south = 2, east = 3 }; char * name[] = {"north", "west", "south", "east"}; struct car_info { int num; enum direction dir; } car[50]; int car_num_total; pthread_t thread[50]; pthread_mutex_t mutex[4]; pthread_cond_t resource[4]; pthread_mutex_t right_block[4]; sem_t deadlock; void init () { for (int i = 0; i < 4; ++i) { pthread_mutex_init(&mutex[i], 0); pthread_cond_init(&resource[i], 0); pthread_mutex_init(&right_block[i], 0); } sem_init(&deadlock, 0, 3); } void * go (void * tempArgument) { struct car_info * arg = tempArgument; pthread_mutex_lock(&mutex[arg->dir]); pthread_cond_wait(&resource[arg->dir], &mutex[arg->dir]); pthread_mutex_unlock(&mutex[arg->dir]); printf("car %d from %s arrives at crossing\\n", arg->num, name[arg->dir]); usleep(1); sem_wait(&deadlock); pthread_mutex_lock(&right_block[arg->dir]); pthread_mutex_lock(&right_block[(arg->dir + 1 ) % 4]); pthread_mutex_unlock(&right_block[(arg->dir + 1 ) % 4]); printf("car %d from %s leaving at crossing\\n", arg->num, name[arg->dir]); pthread_mutex_unlock(&right_block[arg->dir]); sem_post(&deadlock); sleep(1); pthread_mutex_lock(&mutex[arg->dir]); pthread_cond_signal(&resource[arg->dir]); pthread_mutex_unlock(&mutex[arg->dir]); } void delete () { for (int i = 0; i < 4; ++i) { pthread_mutex_destroy(&mutex[i]); pthread_cond_destroy(&resource[i]); pthread_mutex_destroy(&right_block[i]); } sem_destroy(&deadlock); } int main (int argc, char * argv[]) { init(); if (argc == 1) { printf("Please input in cli argument\\n"); return 0; } int car_num_total = strlen(argv[1]); for (int i = 0; i < car_num_total; ++i) { car[i].num = i + 1; switch (argv[1][i]) { case 'n': car[i].dir = north; pthread_create(&thread[i], 0, * go, &car[i]); break; case 'e': car[i].dir = east; pthread_create(&thread[i], 0, * go, &car[i]); break; case 's': car[i].dir = south; pthread_create(&thread[i], 0, * go, &car[i]); break; case 'w': car[i].dir = west; pthread_create(&thread[i], 0, * go, &car[i]); break; default : printf("illegal input\\n"); return 1; } } usleep(1); for (int i = 0; i < 4; ++i) { pthread_cond_signal(&resource[i]); } for (int i = 0; i < 4; ++i) { pthread_join(thread[i], 0); } delete(); return 0; }
1
#include <pthread.h> pthread_mutex_t my_lock; int buf_size_n; int p_count, c_count; int x_num; int consume_num; int p_time, c_time; int buf_counter; int i; sem_t empty; sem_t full; int head, tail; int bbqueue[100]; void producer(void *firstarg) { unsigned long int mytid=pthread_self(); int threadno=*(int*)firstarg; int value; for(i=0;i<p_count;i++){ value = rand() %100; if(buf_counter>=buf_size_n){ sem_post(&full); sem_wait(&empty); } pthread_mutex_lock(&my_lock); if(enqueue(value)==0){ fprintf(stderr,"Error:enqueueing!\\n"); } pthread_mutex_unlock(&my_lock); usleep(p_time); } sem_post(&full); return; } int consumer(void *firstarg) { unsigned long int mytid=pthread_self(); int threadno=*(int*)firstarg; int value; for(i=0; i< consume_num; i++){ if(buf_counter<=0){ sem_post(&empty); sem_wait(&full); } pthread_mutex_lock(&my_lock); value=dequeue(); pthread_mutex_unlock(&my_lock); usleep(ctime); } sem_post(&empty); return value; } int main(int argc, char* argv[]) { int i; int retvalue; if(argc != 7) { fprintf(stderr, "This program requires 6 integer arguments:\\n thread [queue_size] [num_producers] [num_consumers] [num_each_producer_produces] [p_spin_time] [c_spin_time]\\n"); exit(0); } buf_size_n= atoi(argv[1]); p_count = atoi(argv[2]); c_count = atoi(argv[3]); x_num = atoi(argv[4]); p_time = atoi(argv[5]); c_time = atoi(argv[6]); consume_num= p_count* (x_num / c_count); pthread_t producers[p_count]; pthread_t consumers[c_count]; int producerid[p_count]; int consumerid[c_count]; if ((retvalue=pthread_mutex_init(&my_lock,0))<0){ error("Create  mutex  failed!"); exit(-1); } for(i=0;i<p_count;i++){ producerid[i]=i; } for(i=0;i<c_count;i++){ consumerid[i]=i; } fprintf(stderr,"Test program\\nThis program will create %d producers, and %d consumers.\\n Each producer will place %d numbers into a buffer, while \\n each consumer consumes %d numbers from the buffer.\\n", p_count, c_count, x_num, consume_num); fprintf(stderr,"\\n"); for(i=0; i< p_count; i++){ if ((retvalue=pthread_create(&producers[i],0, (void *)producer, (void *)&producerid[i])) < 0){ perror("Unable to create producer thread."); exit(-1); } } for(i=0; i< c_count; i++){ if ((retvalue=pthread_create(&consumers[i],0, (void *)consumer, (void *)&consumerid[i])) < 0){ perror("Unable to create producer thread."); exit(-1); } } for(i=0; i< c_count; i++){ pthread_join(consumers[i],0); } for(i=0; i< p_count; i++){ pthread_join(producers[i],0); } fprintf(stderr,"Main routine exiting: \\n"); } int enqueue(int value){ fprintf(stderr,"Enqueueing %d.\\n",value); if(num_enqueued >= buf_size_n){ printf ("Queue is currently full\\n"); return -1; } if((buf_size_n -num_enqueued) > 0){ bbqueue[head++]=value; } if(head==buf_size_n) {head=0;} num_enqueued++; return 0; } int dequeue (int value){ if (head == tail){ printf ("Queue is empty.\\n"); return 0; } head = (head+1) %(buf_size_n + 1); buf_counter--; return bbqueue[head]; }
0
#include <pthread.h> struct queue_node { void *data; QUEUE_NODE next; }; struct util_queue { QUEUE_NODE head; QUEUE_NODE tail; pthread_mutex_t queue_mutex; }; static UTIL_QUEUE g_util_queue = {0, 0, PTHREAD_MUTEX_INITIALIZER}; static QUEUE_NODE make_queue_node() { QUEUE_NODE lp_node = (QUEUE_NODE)malloc(sizeof(struct queue_node)); if(!lp_node) return 0; lp_node->data = 0; lp_node->next = 0; return lp_node; } static void free_queue_node(QUEUE_NODE lp_node) { free(lp_node); } static void insert_queue_node(UTIL_QUEUE *lp_util_queue, QUEUE_NODE lp_node) { lp_node->next = 0; if(!lp_util_queue->head) { lp_util_queue->head = lp_node; lp_util_queue->tail = lp_node; } else { lp_util_queue->tail->next = lp_node; lp_util_queue->tail = lp_node; } } static void internal_util_queue_clear(UTIL_QUEUE *lp_util_queue) { if(lp_util_queue) { QUEUE_NODE tempnode; while(lp_util_queue->head) { tempnode = lp_util_queue->head; lp_util_queue->head = lp_util_queue->head->next; free_queue_node(tempnode); } lp_util_queue->head = 0; lp_util_queue->tail = 0; } } static int internal_util_queue_append(UTIL_QUEUE *lp_util_queue, void *data) { QUEUE_NODE idle_node; if(!lp_util_queue || !data) return 0; idle_node = make_queue_node(); if(!idle_node) return 0; idle_node->data = data; insert_queue_node(lp_util_queue, idle_node); return 1; } static int internal_util_queue_get_head(UTIL_QUEUE *lp_util_queue, void **data) { QUEUE_NODE lp_node; if(!lp_util_queue || !lp_util_queue->head) return 0; lp_node = lp_util_queue->head; *data = lp_node->data; lp_util_queue->head = lp_util_queue->head->next; free_queue_node(lp_node); return 1; } int util_queue_append(void *data) { pthread_mutex_lock(&g_util_queue.queue_mutex); int result = internal_util_queue_append(&g_util_queue, data); pthread_mutex_unlock(&g_util_queue.queue_mutex); return result; } int util_queue_get_head(void **data) { pthread_mutex_lock(&g_util_queue.queue_mutex); int result = internal_util_queue_get_head(&g_util_queue, data); pthread_mutex_unlock(&g_util_queue.queue_mutex); return result; } void util_queue_clear() { pthread_mutex_lock(&g_util_queue.queue_mutex); internal_util_queue_clear(&g_util_queue); pthread_mutex_unlock(&g_util_queue.queue_mutex); pthread_mutex_destroy(&g_util_queue.queue_mutex); } void util_queue_init() { }
1
#include <pthread.h> pthread_mutex_t lst_lock = PTHREAD_MUTEX_INITIALIZER; struct list * list_init(void) { struct list *list; list = malloc(sizeof *list); if (list == 0) return (0); pthread_cond_init(&list->notempty,0); list->head = 0; list->tail = &list->head; return (list); } int list_enqueue(struct list *list,void (*func)(void *),void *arg) { struct entry *e; e = malloc(sizeof *e); if (e == 0) return (1); e->next = 0; e->func = func; e->arg = arg; pthread_mutex_lock(&lst_lock); *list->tail = e; list->tail = &e->next; pthread_cond_signal(&list->notempty); pthread_mutex_unlock(&lst_lock); return (0); } struct entry * list_dequeue(struct list *list) { struct entry *e; pthread_mutex_lock(&lst_lock); while(list->head == 0) pthread_cond_wait(&list->notempty,&lst_lock); e = list->head; list->head = e->next; if (list->head == 0) list->tail = &list->head; pthread_mutex_unlock(&lst_lock); return (e); }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void){ printf("thread_init\\n"); 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 getenv2(const char *name,char *buf,int buflen){ int i,len,olen; pthread_once(&init_done,thread_init); len=strlen(name); pthread_mutex_lock(&env_mutex); for(i=0;environ[i]!=0;i++){ if((strncmp(name,environ[i],len))==0&&(environ[i][len]=='=')){ printf("---%s\\n",environ[i]); olen=strlen(&environ[i][len+1]); printf("---%d\\n",buflen); if(olen>=buflen){ pthread_mutex_unlock(&env_mutex); return(ENOSPC); } strcpy(buf,&environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return(0); } } pthread_mutex_unlock(&env_mutex); return(0); } pthread_t tid1, tid2; void *thread_fun1(void *arg){ pthread_join(tid1, 0); pthread_join(tid2, 0); char name[]="PATH"; char buf[800]; getenv2(name,buf,200); printf("value=%s\\n",buf); } int main(void){ int err; err = pthread_create(&tid1, 0, thread_fun1, 0); if(err != 0) { printf("create new thread 1 failed\\n"); return ; } err = pthread_create(&tid2, 0, thread_fun1, 0); if(err != 0) { printf("create new thread 1 failed\\n"); return ; } pthread_join(tid1, 0); pthread_join(tid2, 0); exit(0); }
1
#include <pthread.h> sem_t sem_chopsticks[5]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * phi_func(void * n) { int id = (long) n; while (1) { pthread_mutex_lock(&mutex); sem_wait(&sem_chopsticks[id]); sem_wait(&sem_chopsticks[(id + 1) % 5]); pthread_mutex_unlock(&mutex); printf("philosopher %d eating\\n", id); sem_post(&sem_chopsticks[id]); sem_post(&sem_chopsticks[(id + 1) % 5]); printf("philosopher %d thinking\\n\\n", id); } } int main(int argc, char const* argv[]) { pthread_t philosophers[5]; for (int i = 0; i < 5; i++) sem_init(&sem_chopsticks[i], 0, 1); for (int i = 0; i < 5; i++) pthread_create(&philosophers[i], 0, phi_func, (void *) (long) i); for (int i = 0; i < 5; i++) pthread_join(philosophers[i], 0); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; pthread_mutex_t count_mutex; int count = 0; void* thread_body(void* arg) { int num = (int)arg; int send_signal; printf("thread %i starting...\\n", num); if(num%2) { sleep(2); } else { sleep(3); } printf("thread %i finishes job\\n", num); pthread_mutex_lock(&count_mutex); count++; send_signal = (count==5) ? 1 : 0; pthread_mutex_unlock(&count_mutex); printf("thread %i exiting...\\n", num); pthread_exit(0); } int main() { int i; pthread_t threads[5]; time_t start, finish; printf("Main thread starting...\\n"); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&cond, 0); start = time(0); for(i=0 ; i<5 ; i++) { pthread_create(&threads[i], 0, thread_body, (void*)i); } finish = time(0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&count_mutex); pthread_mutex_destroy(&mutex); printf("Main thread exiting...\\n"); printf("Time consumed: %d second(s)\\n", (int)(finish - start)); pthread_exit(0); }
1
#include <pthread.h> extern char **environ; char buf[4096]; pthread_mutex_t env_mutex; pthread_t ntid1, ntid2; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return ENOSPC; } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } pthread_mutex_unlock(&env_mutex); return ENOENT; } void * thr_fn1(void *arg) { puts("here"); pthread_t tid; tid = pthread_self(); printf("My thread1 Id: is %lu\\n", (unsigned long)tid); getenv_r("USER", buf, 4096); puts(buf); return (void *)0; } void * thr_fn2(void *arg) { pthread_t tid; tid = pthread_self(); printf("My thread2 Id: is %lu\\n", (unsigned long)tid); getenv_r("HOME", buf, 4096); puts(buf); return (void *)0; } int main(void) { int err; err = pthread_create(&ntid1, 0, thr_fn1, 0); if (err != 0) puts("error"); err = pthread_create(&ntid2, 0, thr_fn2, 0); sleep(1); puts(buf); exit(0); }
0