text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static void initRocket(struct rocket *); static void animateRocket(struct rocket *); void setRocketsToDead(struct rocket * rockets) { int i; for (i = 0; i < MAX_ROCKETS; i++) rockets[i].isAlive = 0; } void *setupRocket(void *arg) { struct rocket *r = arg; initRocket(r); animateRocket(r); } void initRocket(struct rocket *r) { strncpy(r->message, ROCKET, ROCKET_LEN); r->length = ROCKET_LEN; r->row = LINES - 3; r->delay = 1; r->dir = -1; r->hit = 0; r->isAlive = 1; } void animateRocket(struct rocket *r) { int len = r->length; pthread_mutex_lock(&mx); move(r->row, r->col); addstr(r->message); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); while (1) { usleep(r->delay*TUNIT); pthread_mutex_lock(&mx); move(r->row, r->col); addch(' '); r->row += r->dir; move(r->row, r->col); addstr(r->message); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); if (r->hit == 1) { pthread_mutex_lock(&mx); move(r->row, r->col); addch(' '); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); rocketsLeft++; score++; displayInfo(); break; } if (r->row <= 0) { pthread_mutex_lock(&mx); move(r->row, r->col); addch(' '); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); break; } } r->isAlive = 0; pthread_exit(0); }
1
#include <pthread.h> static int vp9_lf_block_cpu(struct task *tsk, struct task_step *step) { struct lf_blk_param *param = tsk->priv; int mi_row, mi_col; for (mi_row = param->start_mi_row; mi_row < param->end_mi_row; mi_row += param->step_length) { for (mi_col = 0; mi_col < param->cm->mi_cols; mi_col += MI_BLOCK_SIZE) { if (param->upper) { struct lf_blk_param *up = param->upper->priv; pthread_mutex_lock(&up->mutex); while (up->mi_row < mi_row && up->mi_col < mi_col + MI_BLOCK_SIZE*2) { pthread_cond_wait(&up->cond, &up->mutex); } pthread_mutex_unlock(&up->mutex); } vp9_loop_filter_block(param->frame_buffer, param->cm, param->xd, mi_row, mi_col, param->y_only); pthread_mutex_lock(&param->mutex); param->mi_row = mi_row; param->mi_col = mi_col; pthread_mutex_unlock(&param->mutex); pthread_cond_signal(&param->cond); } } pthread_mutex_lock(&param->mutex); param->mi_row += MI_BLOCK_SIZE; param->mi_col += MI_BLOCK_SIZE; pthread_mutex_unlock(&param->mutex); pthread_cond_signal(&param->cond); return 0; } static int vp9_lf_block(struct task *tsk, struct task_step *step, int dev_type) { assert(dev_type == DEV_CPU); return vp9_lf_block_cpu(tsk, step); } static struct task_step lf_steps[] = { { "vp9_lf_block", STEP_KEEP, DEV_CPU, 0, 0, 0, 0, 0, vp9_lf_block, 0, 0 }, }; struct task_steps_pool *lf_steps_pool_get(void) { return task_steps_pool_create(lf_steps, (sizeof(lf_steps) / sizeof(lf_steps[0]))); } struct lf_blk_param *lf_blk_param_get(struct task *tsk) { struct lf_blk_param *param; param = vpx_calloc(1, sizeof(*param)); tsk->priv = param; if (param) { pthread_mutex_init(&param->mutex, 0); pthread_cond_init(&param->cond, 0); } return param; } void lf_blk_param_put(struct task *tsk, struct lf_blk_param *param) { pthread_mutex_destroy(&param->mutex); pthread_cond_destroy(&param->cond); vpx_free(param); }
0
#include <pthread.h> { int key; struct __node_t *next; } node_t; { node_t *head; pthread_mutex_t lock; } list_t; void list_init(list_t *l) { l->head = 0; pthread_mutex_init(&l->lock, 0); } int list_insert(list_t *l, int key) { node_t *new = malloc(sizeof *new); if(new == 0) { perror("malloc"); return -1; } new->key = key; pthread_mutex_lock(&l->lock); new->next = l->head; l->head = new; pthread_mutex_unlock(&l->lock); return 0; } int list_lookup(list_t *l, int key) { int rv = -1; pthread_mutex_lock(&l->lock); node_t *curr = l->head; while(curr) { if(curr->key == key) { rv = 0; break; } curr = curr->next; } pthread_mutex_lock(&l->lock); return rv; } int main() { return 0; }
1
#include <pthread.h> struct foo { int id; int refs; struct foo* next; pthread_mutex_t mutex; }; int hash(int id) { return id % 10; } struct foo* map[10]; pthread_mutex_t hash_lock; struct foo* alloc(int id) { struct foo* p; if ((p = (struct foo*)malloc(sizeof(struct foo))) != 0) { p->id = id; p->refs = 1; if (pthread_mutex_init(&p->mutex, 0) != 0) { free(p); return 0; } printf("pid %ld tid %ld alloc id %d\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), id); } int index = hash(id); pthread_mutex_lock(&hash_lock); p->next = map[index]; map[index] = p; pthread_mutex_unlock(&hash_lock); return p; } void hold(struct foo* p) { pthread_mutex_lock(&p->mutex); p->refs++; pthread_mutex_unlock(&p->mutex); } struct foo* find(int id) { struct foo* p; pthread_mutex_lock(&hash_lock); for (p = map[hash(id)]; p != 0; p = p->next) { if (p->id = id) { break; } } pthread_mutex_unlock(&hash_lock); return p; } void release(struct foo* p) { if (p == 0) { return; } pthread_mutex_lock(&p->mutex); if (p->refs == 1) { pthread_mutex_unlock(&p->mutex); pthread_mutex_lock(&hash_lock); pthread_mutex_lock(&p->mutex); if (p->refs != 1) { p->refs--; pthread_mutex_unlock(&p->mutex); pthread_mutex_unlock(&hash_lock); } int index = hash(p->id); struct foo* f = map[index]; if (f == p) { map[index] = p->next; } else { while (f->next != p) { f = f->next; } f->next = p->next; } pthread_mutex_unlock(&hash_lock); pthread_mutex_unlock(&p->mutex); pthread_mutex_destroy(&p->mutex); int id = p->id; free(p); printf("pid %ld tid %ld free id %d\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), id); } else { p->refs--; pthread_mutex_unlock(&p->mutex); } } void* thread_task(void* arg) { int i; for (i = 0; i < 10; i++) { alloc(i + 1); } } int main(int argc, char* argv[]) { pthread_mutex_init(&hash_lock, 0); pthread_t tid; int err = 0; int i; err = pthread_create(&tid, 0, thread_task, 0); if (err != 0) { err_exit(err, "can't create thread"); } sleep(1); for (i = 0; i < 10; i++) { struct foo* p = find(i + 1); release(p); } pthread_join(tid, 0); return 0; }
0
#include <pthread.h> int main() { printf("Do not support this kind of process lock\\n"); return 0; int pid = 0; int shm_id = 0; int ret = 0; struct shmid_ds buf; int* x = 0; char* shmaddr = 0; char* addnum = "myadd"; void* ptr = 0; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; ret = pthread_mutex_init(&mutex, 0); assert(ret == 0); ret = pthread_mutexattr_init(&mutexattr); assert(ret == 0); ret = pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED); assert(ret == 0); assert(ret == 0); shm_id = shmget(IPC_PRIVATE, 4, IPC_CREAT|0600); assert(shm_id != -1); pid = fork(); if (pid == 0) { shmaddr = (char*)shmat(shm_id, 0, 0); assert((int)shmaddr != -1); x = (int *)shmaddr; for (int i=0; i<10; i++) { pthread_mutex_lock(&mutex); (*x)++; printf("x++: %d\\n", *x); pthread_mutex_unlock(&mutex); sleep(1); } ret = shmdt(shmaddr); assert(ret == 0); } else { int flag = shmctl( shm_id, IPC_STAT, &buf); assert(flag != -1); printf("shm_segsz =%d bytes\\n", buf.shm_segsz ); printf("parent pid=%d, shm_cpid = %d \\n", getpid(), buf.shm_cpid ); printf("chlid pid=%d, shm_lpid = %d \\n", pid , buf.shm_lpid ); shmaddr = (char*)shmat(shm_id, 0, 0); assert((int)shmaddr != -1); x = (int *)shmaddr; for (int i=0; i<10; i++) { pthread_mutex_lock(&mutex); (*x) += 2; printf("x+=2: %d\\n",*x); pthread_mutex_unlock(&mutex); sleep(1); } ret = shmdt(shmaddr); assert(ret == 0); ret = shmctl(shm_id, IPC_RMID, 0); assert(ret == 0); } return(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t transferCond; { unsigned int id; int money; bool isFree; pthread_cond_t cond; } bankAccount; { bankAccount* src; bankAccount* target; int numberOfMoney; } moneyTransfer; { bankAccount* target; int numberOfMoney; } addMoney; bankAccount* createAccount(int id, int money) { bankAccount* account = (bankAccount*)malloc(sizeof(bankAccount)); account->id = id; account->money = money; account->isFree = 1; pthread_cond_init(&(account->cond), 0); return account; } moneyTransfer* createTransfer(bankAccount* src, bankAccount* target, int numberOfMoney) { moneyTransfer* transfer = (moneyTransfer*)malloc(sizeof(moneyTransfer)); transfer->src = src; transfer->target = target; transfer->numberOfMoney = numberOfMoney; return transfer; } addMoney* createAdder(bankAccount* target, int numberOfMoney) { addMoney* add = (addMoney*)malloc(sizeof(addMoney)); add->target = target; add->numberOfMoney = numberOfMoney; return add; } void* addToAccount(void* arg) { addMoney* money = (addMoney*)arg; bankAccount* target = money->target; for (int i = 0; i < 6; i++) { pthread_mutex_lock(&mutex); while (1) { if (target->isFree) { target->isFree = 0; pthread_mutex_unlock(&mutex); break; } else { pthread_cond_wait(&(target->cond), &mutex); } } int cache = target->money; usleep(rand() % 1000); target->money = cache + money->numberOfMoney; printf("Dodaje %d pln do konta nr: %d \\nStan konta: %d \\n\\n", money->numberOfMoney, target->id, target->money); pthread_mutex_lock(&mutex); target->isFree = 1; pthread_cond_signal(&(target->cond)); pthread_cond_signal(&(transferCond)); pthread_mutex_unlock(&mutex); } } void* transferMoney(void* arg) { moneyTransfer* transfer = (moneyTransfer*)arg; bankAccount* src = transfer->src; bankAccount* target = transfer->target; for (int i = 0; i < 6; i++) { pthread_mutex_lock(&mutex); while (1) { if (target->isFree && src->isFree) { target->isFree = 0; src->isFree = 0; pthread_mutex_unlock(&mutex); break; } else { pthread_cond_wait(&(transferCond), &mutex); } } int srcCache = src->money; int targetCache = target->money; usleep(rand() % 1000); src->money = srcCache - transfer->numberOfMoney; target->money = targetCache + transfer->numberOfMoney; printf("\\n przelew: %d \\n", transfer->numberOfMoney); printf("Z konta nr: %d --> stan konta: %d \\n", src->id, src->money); printf("Do konta nr: %d --> stan konta: %d \\n", target->id, target->money); pthread_mutex_lock(&mutex); src->isFree = 1; target->isFree = 1; pthread_cond_signal(&(transferCond)); pthread_cond_signal(&(src->cond)); pthread_cond_signal(&(target->cond)); pthread_mutex_unlock(&mutex); } } int main() { int i; time_t t; i = time(&t); srand(i); if (pthread_mutex_init(&mutex, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } int threadNumber = 5; pthread_t addFirstAccountThread[threadNumber]; pthread_t addSecondAccountThread[threadNumber]; pthread_t transferFirstThread[threadNumber]; pthread_t transferSecondThread[threadNumber]; int returnThread; bankAccount* firstAccount = createAccount(1, 0); bankAccount* secondAccount = createAccount(2, 0); addMoney* addToFirst = createAdder(firstAccount, 100); addMoney* addToSecond = createAdder(secondAccount, 100); moneyTransfer* fromFirstTransfer = createTransfer(firstAccount, secondAccount, 50); moneyTransfer* fromSecondTransfer = createTransfer(secondAccount, firstAccount, 150); for (int i = 0; i < threadNumber; i++) { pthread_create(&(addFirstAccountThread[i]), 0, addToAccount, (void*)addToFirst); pthread_create(&(addSecondAccountThread[i]), 0, addToAccount, (void*)addToSecond); pthread_create(&(transferFirstThread[i]), 0, transferMoney, (void*)fromFirstTransfer); pthread_create(&(transferSecondThread[i]), 0, transferMoney, (void*)fromSecondTransfer); } for (int i = 0; i < threadNumber; i++) { pthread_join(addFirstAccountThread[i], 0); pthread_join(addSecondAccountThread[i], 0); pthread_join(transferFirstThread[i], 0); pthread_join(transferSecondThread[i], 0); } printf("\\n====================KONIEC====================\\n"); printf("Konto nr: %d --> stan konta: %d \\n", firstAccount->id, firstAccount->money); printf("Konto nr: %d --> stan konta: %d \\n", secondAccount->id, secondAccount->money); pthread_mutex_destroy(&mutex); exit(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); if (enqueue_flag) { for(i=0; i<(400); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(400); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR:__VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR:__VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char s[10000]; int flag; void *producer (void *a) { int i, j; flag = 0; pthread_mutex_lock (&mutex); for (i = 0; i < 10000; i++) { s[i] = 'p'; for (j = 0; j < 10000; j++); } pthread_mutex_unlock (&mutex); } void *consumer (void *a) { int i, j; flag = 1; pthread_mutex_lock (&mutex); for (i = 0; i < 10000; i++) { s[i] = 'c'; for (j = 0; j < 10000; j++); } pthread_mutex_unlock (&mutex); } int main () { pthread_t pid, cid; int corrupt, i; while (1) { pthread_create (&pid, 0, producer, 0); pthread_create (&cid, 0, consumer, 0); pthread_join (pid, 0); pthread_join (cid, 0); corrupt = 0; for (i = 0; i < 10000 - 1; i++) { if (s[i] != s[i + 1]){ corrupt = 1; break; } } if (corrupt) printf ("Memory is corrupted\\n"); else printf ("Not corrupted\\n"); } return 0; }
0
#include <pthread.h> int n; int squares; struct { int i, j; } moves[] = {{0, -3}, {0, 3}, {-3, 0}, {3, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; int num_moves = sizeof(moves)/sizeof(moves[0]); pthread_mutex_t sol_lock; int solutions = 0; int max_depth = 0; unsigned long total_iter = 0; int reachable(int *board, int i, int j) { int move; for(move = 0; move < num_moves; ++move) { int new_i = i + moves[move].i; int new_j = j + moves[move].j; if(new_i < 0 || new_j < 0 || new_i >= n || new_j >= n) continue; if(board[new_i * n + new_j] == 0) return 1; } return 0; } unsigned long iter_report = 1024; void search(int *board, int i, int j, int iter) { if(++total_iter == iter_report) { printf("%ld iterations\\n", total_iter); fflush(stdout); iter_report <<= 1; } if(iter > max_depth) { max_depth = iter; printf("max_depth: %d\\n", max_depth); int a; for(a = 0; a < n; ++a) { int b; for(b = 0; b < n; ++b) printf("(%4d)", board[a*n+b]); putchar('\\n'); } fflush(stdout); } iter++; int move; for(move = 0; move < num_moves; ++move) { int new_i = i + moves[move].i; int new_j = j + moves[move].j; if(new_i < 0 || new_j < 0 || new_i >= n || new_j >= n) continue; if(board[new_i * n + new_j] != 0) continue; board[new_i*n+new_j] = iter; if(iter == squares) { pthread_mutex_lock(&sol_lock); ++solutions; printf("solution %d:\\n", solutions); int a; for(a = 0; a < n; ++a) { int b; for(b = 0; b < n; ++b) printf("(%4d)", board[a*n+b]); putchar('\\n'); } pthread_mutex_unlock(&sol_lock); } else { int invalid_move = 0; int check; for(check = 0; check < num_moves; ++check) { int check_i = i + moves[check].i; int check_j = j + moves[check].j; if(check_i < 0 || check_j < 0 || check_i >= n || check_j >= n) continue; if(board[check_i * n + check_j] != 0) continue; if(!reachable(board, check_i, check_j)) { invalid_move = 1; break; } } if(!invalid_move) search(board, new_i, new_j, iter); } board[new_i*n+new_j] = 0; } } int num_threads = 1; pthread_mutex_t job_lock = PTHREAD_MUTEX_INITIALIZER; int iter_i = 0, iter_j = -1; pthread_mutex_t barrier_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t barrier_signal = PTHREAD_COND_INITIALIZER; int barrier_count = 0; void barrier() { pthread_mutex_lock(&barrier_lock); barrier_count++; if(barrier_count == num_threads) { pthread_cond_broadcast(&barrier_signal); barrier_count = 0; } else pthread_cond_wait(&barrier_signal, &barrier_lock); pthread_mutex_unlock(&barrier_lock); } void *run(void *args) { int *board = calloc(sizeof(int), squares); while(1) { pthread_mutex_lock(&job_lock); iter_j++; if(iter_j > n/2) { iter_i ++; if(iter_i > n/2) { pthread_mutex_unlock(&job_lock); break; } iter_j = iter_i; } pthread_mutex_unlock(&job_lock); board[iter_i*n + iter_j] = 1; printf("search(%d, %d, 1);\\n", iter_i, iter_j); search(board, iter_i, iter_j, 1); board[iter_i*n + iter_j] = 0; } free(board); barrier(); return 0; } int main(int argc, char *argv[]) { if(argc != 2 && argc != 3) { fprintf(stderr, "usage: %s n [num_threads]\\n", argv[0]); return -1; } n = atoi(argv[1]); if(argc == 3) num_threads = atoi(argv[2]); squares = n*n; fputs(argv[0], stdout); putchar(' '); puts(argv[1]); puts("searching for solutions:"); pthread_t threads[num_threads]; int i; for(i = 0; i < num_threads-1; ++i) { pthread_create(&threads[i], 0, &run, 0); } run(0); printf("%d solutions found\\n", solutions); return 0; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo *foo_alloc(int id) { struct foo *fp; int idx; if((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); return (fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if(fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_lock(&hashlock); return (fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; } else { while(tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> struct dist_tab_entry { char * name; int len; struct timespec expiration; int hops; }; struct dist_table { int size; struct bitmap * valid; pthread_mutex_t table_lock; struct dist_tab_entry * table; }; struct dist_table g_dist_tab; int dtab_init(int size) { g_dist_tab.size = size; g_dist_tab.valid = bit_create(size); pthread_mutex_init(&g_dist_tab.table_lock, 0); g_dist_tab.table = (struct dist_tab_entry * ) malloc(sizeof(struct dist_tab_entry) * size); int i; for (i = 0; i < size; i++) { g_dist_tab.table[i].name = 0; } return 0; } int dtab_getHops(char * name) { int index = HASH(name) % g_dist_tab.size; int hops = -1; pthread_mutex_lock(&g_dist_tab.table_lock); if (bit_test(g_dist_tab.valid, index) == 1) { struct timespec now; ts_fromnow(&now); if (ts_compare(&now, &g_dist_tab.table[index].expiration) < 0) { hops = g_dist_tab.table[index].hops; } } pthread_mutex_unlock(&g_dist_tab.table_lock); return hops; } int dtab_setHops(char * name, int hops) { int index = HASH(name) % g_dist_tab.size; pthread_mutex_lock(&g_dist_tab.table_lock); if (bit_test(g_dist_tab.valid, index) == 1) { free(g_dist_tab.table[index].name); g_dist_tab.table[index].name = malloc(strlen(name)); strcpy(g_dist_tab.table[index].name, name); } else { g_dist_tab.table[index].name = malloc(strlen(name)); strcpy(g_dist_tab.table[index].name, name); bit_set(g_dist_tab.valid, index); } pthread_mutex_unlock(&g_dist_tab.table_lock); return 0; }
1
#include <pthread.h> int pthread_setcancelstate (int state, int *oldstate) { struct pthread_internal_t *p = (struct pthread_internal_t*)pthread_self(); int newflags; pthread_init(); switch (state) { default: return EINVAL; case PTHREAD_CANCEL_ENABLE: case PTHREAD_CANCEL_DISABLE: break; } pthread_mutex_lock (&p->cancel_lock); if (oldstate) *oldstate = p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_ENABLE; if(state == PTHREAD_ATTR_FLAG_CANCEL_ENABLE) p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_ENABLE; else p->attr.flags &= ~PTHREAD_ATTR_FLAG_CANCEL_ENABLE; newflags=p->attr.flags; pthread_mutex_unlock (&p->cancel_lock); if((newflags & PTHREAD_ATTR_FLAG_CANCEL_PENDING) && (newflags & PTHREAD_ATTR_FLAG_CANCEL_ENABLE) && (newflags & PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS)) __pthread_do_cancel(p); return 0; }
0
#include <pthread.h> static int cmp_by_addr(const void * d1,const void *d2) { struct conn * c1=(struct conn *) d1; struct conn * c2=(struct conn *) d2; return sock_cmpaddr((struct sockaddr*)&c1->addr,(struct sockaddr*)&c2->addr,1); } static int cmp_by_session_id(const void *d1, const void *d2) { struct conn * c1=(struct conn *) d1; struct conn * c2=(struct conn *) d2; return memcmp(c1->session_id,c2->session_id,16); } struct connlist * connlist_create(int len) { struct connlist * cl = malloc(sizeof(struct connlist)); if (!cl) return 0; cl->by_addr = mavl_create(cmp_by_addr,0); if (!cl->by_addr){ free(cl); return 0; } cl->by_session_id = mavl_create(cmp_by_session_id,0); if (pthread_mutex_init(&cl->connlist_mutex,0)){ mavl_destroy(cl->by_addr); free(cl); return 0; }; cl->len=len; return cl; } void connlist_lock(struct connlist * cl) { pthread_mutex_lock(&cl->connlist_mutex); } void connlist_unlock(struct connlist * cl) { pthread_mutex_unlock(&cl->connlist_mutex); } void connlist_destroy(struct connlist * cl) { if (!cl) return; if (cl->by_addr) mavl_destroy(cl->by_addr); pthread_mutex_destroy(&cl->connlist_mutex); free(cl); } struct conn * connlist_get(struct connlist * cl, const struct sockaddr * addr) { struct conn search; sock_copyaddr(&search.addr,addr); return mavl_get(cl->by_addr,&search); } struct conn * connlist_add(struct connlist * cl, struct conn * conn) { if ( cl->len!=0) if (cl->by_addr->count>=cl->len) return 0; conn->connlist=cl; return mavl_add(cl->by_addr,conn); } struct conn * connlist_get_by_session_id(struct connlist *cl, struct conn * conn) { return mavl_get(cl->by_session_id,conn); } struct conn * connlist_add_by_session_id(struct connlist * cl, struct conn * conn) { return mavl_add(cl->by_session_id,conn); } void connlist_remove(struct connlist *cl,struct conn * conn) { mavl_del(cl->by_session_id,conn); mavl_del(cl->by_addr,conn); }
1
#include <pthread.h> struct list_node { long value; struct list_node *next; }; static struct list_node **list_head; static struct list_node **free_head; static pthread_mutex_t *mutex; void print_list(void) { struct list_node *curr = *list_head; while (curr != 0) { printf("%ld -> ", curr->value); curr = curr->next; } printf("NULL\\n"); } void do_work(void) { int i; for (i = 0; i < 2; i++) { pthread_mutex_lock(mutex); struct list_node *n = *free_head; if (n == 0) { pthread_mutex_unlock(mutex); assert(0); } *free_head = (*free_head)->next; n->value = (long) getpid(); n->next = *list_head; *list_head = n; print_list(); pthread_mutex_unlock(mutex); } for (i = 0; i < 2; i++) { pthread_mutex_lock(mutex); struct list_node *n = *list_head; *list_head = (*list_head)->next; n->next = *free_head; *free_head = n; pthread_mutex_unlock(mutex); } } int main(void) { void *ptr; size_t region_sz = 0; region_sz += sizeof(**list_head)*1024; region_sz += sizeof(list_head)+sizeof(free_head); region_sz += sizeof(*mutex); ptr = mmap(0, region_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); if (ptr == MAP_FAILED) { perror("mmap(2) failed"); exit(1); } mutex = ptr; free_head = (struct list_node **) (((char *) ptr)+sizeof(*mutex)); list_head = free_head+1; *free_head = (struct list_node *) (list_head+1); *list_head = 0; int i; struct list_node *curr; for (i = 0, curr = *free_head; i < 1024 -1; i++, curr++) { curr->next = curr+1; } curr->next = 0; pthread_mutexattr_t mutex_attr; if (pthread_mutexattr_init(&mutex_attr) < 0) { perror("Failed to initialize mutex attributes"); exit(1); } if (pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED) < 0) { perror("Failed to change mutex attributes"); exit(1); } if (pthread_mutex_init(mutex, &mutex_attr) < 0) { perror("Failed to initialize mutex"); exit(1); } for (i = 0; i < 2; i++) { pid_t pid; if ((pid = fork()) < 0) { perror("fork(2) error"); exit(1); } if (pid == 0) { do_work(); return 0; } } for (i = 0; i < 2; i++) { if (wait(0) < 0) { perror("wait(2) error"); } } print_list(); assert(*list_head == 0); return 0; }
0
#include <pthread.h> void *cgi_thread_handler(void *arg) { char buf[MAXCMDLEN]; int led_flag; int beep_flag; while (1) { pthread_mutex_lock(&SHM->cgi_mutex_start); while (0 == SHM->cgi_emit_start) { pthread_cond_wait(&SHM->cgi_cond_start, &SHM->cgi_mutex_start); } if (0 < SHM->cgi_emit_start) { SHM->cgi_emit_start--; } memset(buf, 0, sizeof(buf)); strcpy(buf, SHM->cgi_cmd); pthread_mutex_unlock(&SHM->cgi_mutex_start); if (0 == strcmp(buf, "LED_ON")) { pthread_mutex_lock(&SHM->led_mutex_status); if (0 == SHM->led_emit_status) { SHM->led_emit_status++; } pthread_mutex_unlock(&SHM->led_mutex_status); pthread_mutex_lock(&SHM->led_mutex_start); led_flag = (0 == SHM->led_emit_start); if (0 == SHM->led_emit_start) { SHM->led_emit_start++; } pthread_mutex_unlock(&SHM->led_mutex_start); if (1 == led_flag) { pthread_cond_signal(&SHM->led_cond_start); } } if (0 == strcmp(buf, "LED_OFF")) { pthread_mutex_lock(&SHM->led_mutex_status); if (0 < SHM->led_emit_status) { SHM->led_emit_status--; } pthread_mutex_unlock(&SHM->led_mutex_status); pthread_mutex_lock(&SHM->led_mutex_start); led_flag = (0 == SHM->led_emit_start); if (0 == SHM->led_emit_start) { SHM->led_emit_start++; } pthread_mutex_unlock(&SHM->led_mutex_start); if (1 == led_flag) { pthread_cond_signal(&SHM->led_cond_start); } } if (0 == strcmp(buf, "BEEP_ON")) { pthread_mutex_lock(&SHM->beep_mutex_status); if (0 == SHM->beep_emit_status) { SHM->beep_emit_status++; } pthread_mutex_unlock(&SHM->beep_mutex_status); pthread_mutex_lock(&SHM->beep_mutex_start); beep_flag = (0 == SHM->beep_emit_start); if (0 == SHM->beep_emit_start) { SHM->beep_emit_start++; } pthread_mutex_unlock(&SHM->beep_mutex_start); if (1 == beep_flag) { pthread_cond_signal(&SHM->beep_cond_start); } } if (0 == strcmp(buf, "BEEP_OFF")) { pthread_mutex_lock(&SHM->beep_mutex_status); if (0 < SHM->beep_emit_status) { SHM->beep_emit_status--; } pthread_mutex_unlock(&SHM->beep_mutex_status); } } }
1
#include <pthread.h> int ticketcount=11; pthread_mutex_t lock; void *salewinds1(void *args) { while(1) { pthread_mutex_lock(&lock); if(ticketcount >0) { printf("windows1 start sales!the ticket is:%d\\n",ticketcount); sleep(2); ticketcount--; printf("sales ticket finish!the last ticket is:%d\\n",ticketcount); } else { pthread_mutex_unlock(&lock); pthread_exit(0); } pthread_mutex_unlock(&lock); sleep(1); } } void *salewinds2(void *args) { while(1) { pthread_mutex_lock(&lock); if(ticketcount>0) { printf("windows2 start sales!the ticket is:%d\\n",ticketcount); sleep(2); ticketcount--; printf("sales ticket finish!the last ticket is:%d\\n",ticketcount); } else { pthread_mutex_unlock(&lock); pthread_exit(0); } pthread_mutex_unlock(&lock); sleep(1); } } int main() { pthread_t pthid1=0; pthread_t pthid2=0; pthread_create(&pthid1,0,salewinds1,0); pthread_create(&pthid2,0,salewinds2,0); pthread_join(pthid1,0); pthread_join(pthid2,0); return 0; }
0
#include <pthread.h> extern int startWifiSet(void); static pthread_mutex_t wifi_mutex; static pthread_t thdWifi = 0; static int wifiRunFlag = 0; static volatile int curWifiMode = WIFI_NULL_MODE; static int bkWifiMode = WIFI_NULL_MODE; static volatile int needHttpServer = 0; int getWifiState(void) { return curWifiMode; } int setWiFiState(int mode) { int ret=0; if(curWifiMode == mode) return ret; switch(mode) { case WIFI_OFF_MODE: case WIFI_NULL_MODE: wifiledset(COM_LED_WIFI_NULL); ret = SetWifiMode(WIFI_OFF); break; case WIFI_AP_MODE: SetWifiMode(WIFI_OFF); wifiledset(COM_LED_WIFI_AP_MODE); ret = SetWifiMode(WIFI_AP); if (ret) { printf("call SetWifiMode(WIFI_AP) fail\\n"); }else printf("wifi enter ap mode\\n"); needHttpServer = 1; break; case WIFI_STA_MODE: wifiledset(COM_LED_WIFI_SEARCH); SetWifiMode(WIFI_OFF); ret = SetWifiMode(WIFI_STA); if(ret) { printf("call SetWifiMode(STA) fail\\n"); }else printf("wifi enter STA mode\\n"); break; default: printf("set wifi mode wrong :%d\\n",mode); return -1; break; } pthread_mutex_lock(&wifi_mutex); curWifiMode = mode; pthread_mutex_unlock(&wifi_mutex); return ret; } void needResetWifi(void) { if(curWifiMode != WIFI_AP_MODE) { setWiFiState(WIFI_AP_MODE); resetSuspendtimer(); }else { setWiFiState(WIFI_STA_MODE); resetSuspendtimer(); } } static int gtimeok = 0; static int gwifiok = 0; int getWifiConnected(void) { if(getWifiState() != WIFI_STA_MODE) gwifiok = 0; return gwifiok; } void *thread_wifi(void *pHand) { static int wifiTimeout; int ret; while (wifiRunFlag) { switch(getWifiState()) { case WIFI_AP_MODE: if (needHttpServer) { needHttpServer = 0; printf("now ,enter wifi ssid & pwd.\\n"); startWifiPwdSet(); if(getsuspendtimer()>0) { setpauseSuspendtimer(1); printf("wifi exit ap mode,enter sta mode\\n"); setWiFiState(WIFI_STA_MODE); resetSuspendtimer(); setpauseSuspendtimer(0); } } break; case WIFI_STA_MODE: ret = GetWifiStaStates(); if(ret != COMPLETED) gwifiok = 0; if(ret == COMPLETED) { wifiledset(COM_LED_WIFI_OK); wifiTimeout = 0; gwifiok = 1; if(!gtimeok) { if(!getNetTime()) gtimeok = 1; } }else if(++wifiTimeout > ((1000/500)*10) ) { wifiledset(COM_LED_WIFI_SEARCH); printf("wifi:%d\\n",ret); wifiTimeout = 0; setpauseSuspendtimer(1); SetWifiMode(WIFI_OFF); SetWifiMode(WIFI_STA); setpauseSuspendtimer(0); } break; } msleep(500); } return 0; } int wifiSuspend(void) { if(curWifiMode == WIFI_AP_MODE) { stop_http_server(); msleep(50); curWifiMode = WIFI_STA_MODE; } bkWifiMode = curWifiMode; setWiFiState(WIFI_OFF_MODE); msleep(50); return 0; } int wifiResume(void) { return setWiFiState(bkWifiMode); } int wifiDevInit(void) { int res; char ssid[SYSTEM_DEMO_SSID_MAXLEN]; char pwd[SYSTEM_DEMO_PSW_MAXLEN]; res = pthread_mutex_init(&wifi_mutex, 0); if (res != 0) { printf("pthread_mutex_init failed\\n"); return -1; } wifiRunFlag = 1; res = pthread_create(&thdWifi, 0, thread_wifi, 0); if (res != 0) { printf("thread_wifi pthread_create failed\\n"); return res; } printf("wifi thread create ok!\\n"); if(!GetWifiConfig(ssid,pwd)) { SetWifiStaAccount(0, ssid, pwd); setWiFiState(WIFI_STA_MODE); } return 0; } int wifiDevDeinit(void) { void *value; wifiRunFlag = 0; pthread_mutex_unlock(&wifi_mutex); msleep(10); if (thdWifi) { pthread_join(thdWifi, &value); thdWifi = 0; } pthread_mutex_destroy(&wifi_mutex); printf("wifi thread Deinit ok!\\n"); return 0; }
1
#include <pthread.h> pthread_cond_t VC[5]; pthread_mutex_t M = PTHREAD_MUTEX_INITIALIZER; int estado[5]; int actualiza (int i) { if ((estado[(i - 1) % 5] != 3) && (estado[i] == 2) && (estado[(i + 1) % 5] != 3)) { estado[i] = 3; pthread_cond_signal(&VC[i]); } return 0; } void palillos_init () { int i; pthread_mutex_init(&M, 0); for (i = 0; i < 5; i++) { pthread_cond_init(&VC[i], 0); estado[i] = 1; } } void toma_palillos (int i) { pthread_mutex_lock(&M); estado[i] = 2; actualiza(i); while (estado[i] == 2) pthread_cond_wait(&VC[i], &M); pthread_mutex_unlock(&M); } void suelta_palillos (int i) { pthread_mutex_lock(&M); estado[i] = 1; actualiza((i - 1) % 5); actualiza((i + 1) % 5); pthread_mutex_unlock(&M); } void come(int i) { printf("El filosofo %d esta comiendo\\n", i); } void piensa(int i) { printf("El filosofo %d esta pensando\\n", i); } void *filosofo(void *arg) { int self = *(int *) arg; for (;;) { piensa(self); toma_palillos(self); come(self); suelta_palillos(self); } } int main() { int i; pthread_t th[5]; pthread_attr_t attr; palillos_init(); for (i=0; i<5; i++) pthread_create(&th[i], &attr, filosofo, (int*) &i); for (i=0; i<5; i++) pthread_join(th[i],0); }
0
#include <pthread.h> int recordSize = 1024; int threadsNr; char *fileName; int fd; int numOfRecords; int creatingFinished = 0; char *word; int rc; int someonefound = 0; int detachedNr = 0; pthread_key_t key; pthread_t *threads; int *wasJoin; pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER; long gettid() { return syscall(SYS_gettid); } void signalHandler(int signal){ if(signal == SIGUSR1) { printf("Received SIGUSR1\\n"); } else if(signal == SIGTERM) { printf("Received SIGTERM\\n"); } printf("PID: %d TID: %ld\\n", getpid(), pthread_self()); return; } void* threadFun(void *oneArg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_t threadHandle = pthread_self(); pthread_t threadID = gettid(); printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID); char **readRecords; readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_setspecific(key, readRecords); readRecords = pthread_getspecific(key); while(!creatingFinished); int finish = 0; int moreBytesToRead = 1; int numOfReadedBytes; while(!finish && moreBytesToRead) { pthread_mutex_lock(&mutexForRecords); for(int i=0;i<numOfRecords;i++) { numOfReadedBytes = read(fd, readRecords[i], 1024); if(numOfReadedBytes==-1) { perror("error while reading in threadFun"); exit(1); } if(numOfReadedBytes<1024) moreBytesToRead = 0; } pthread_mutex_unlock(&mutexForRecords); for(int i = 0; i<numOfRecords; i++) { if(strstr(readRecords[i], word) != 0) { char recID[10]; strncpy(recID, readRecords[i], 10); printf("%ld: found word in record number %d\\n", threadID, atoi(recID)); } } } if(pthread_detach(threadHandle) != 0) { perror("pthread_detach error"); exit(1); } detachedNr++; pthread_exit(0); } int openFile(char *fileName) { int fd = open(fileName, O_RDONLY); if(fd == -1) { perror("file open error"); exit(-1); } else return fd; } void createThread(pthread_t *thread) { rc = pthread_create(thread, 0, threadFun, 0); if(rc != 0) { perror("thread create error"); exit(-1); } } int main(int argc, char *argv[]) { if(argc!=6) { puts("Bad number of arguments"); puts("Appropriate arguments:"); printf("[program] [threads nr] [file] \\n"); printf("[records nr] [word to find] [test nr]"); return 1; } printf("MAIN -> PID: %d TID: %ld\\n", getpid(), pthread_self()); threadsNr = atoi(argv[1]); fileName = calloc(1,sizeof(argv[2])); fileName = argv[2]; numOfRecords = atoi(argv[3]); word = calloc(1,sizeof(argv[4])); word = argv[4]; int test = atoi(argv[5]); if(test != 1 && test != 2 && test != 3 && test != 4) { puts("wrong test number"); exit(1); } fd = openFile(fileName); char **readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_key_create(&key, 0); threads = calloc(threadsNr, sizeof(pthread_t)); wasJoin = calloc(threadsNr, sizeof(int)); for(int i=0; i<threadsNr; i++) { createThread(&threads[i]); } creatingFinished = 1; sigset_t set; sigfillset(&set); pthread_sigmask(SIG_SETMASK, &set, 0); if(test == 1) { puts("sending SIGUSR1 signal"); sleep(2); kill(getpid(),SIGUSR1); } if(test == 2) { puts("sending SIGTERM signal"); sleep(2); kill(getpid(),SIGTERM); } if(test == 3) { puts("sending SIGKILL signal"); kill(getpid(),SIGKILL); } if(test == 4) { puts("sending SIGSTOP signal"); kill(getpid(),SIGSTOP); } while(detachedNr != threadsNr) { usleep(100); } printf("End of program\\n\\n"); if(close(fd)<0) { perror("close error"); return 1; } free(threads); return 0; }
1
#include <pthread.h> int do_debug = 0; int do_thread = 0; int do_stdin = 0; int do_sleep = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t rand_mutex = PTHREAD_MUTEX_INITIALIZER; int threadcount = 0; struct sockets { int local; FILE *in, *out; }; struct sockets *get_sockets(int); int socket_setup(void); int debug(char *, ...); int fail(char *, ...); int warn(char *, ...); int roll_die(int); void *roll_dice(void *); void spawn(struct sockets *); int debug(char *fmt, ...) { va_list ap; int r; __builtin_va_start((ap)); if (do_debug) { r = vfprintf(stderr, fmt, ap); } else { r = 0; } ; return r; } int warn(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); ; return r; } int fail(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); exit(1); ; return r; } int roll_die(int n) { int r; pthread_mutex_lock(&rand_mutex); r = rand() % n + 1; pthread_mutex_unlock(&rand_mutex); return r; } void * roll_dice(void *v) { struct sockets *s = v; char inbuf[512]; if (!s || !s->out || !s->in) return 0; fprintf(s->out, "enter die rolls, or q to quit\\n"); while (fgets(inbuf, sizeof(inbuf), s->in) != 0) { int dice; int size; if (inbuf[0] == 'q') { fprintf(s->out, "buh-bye!\\n"); if (s->local == 0) { shutdown(fileno(s->out), SHUT_RDWR); } fclose(s->out); fclose(s->in); if (s->local == 0) { free(s); } pthread_mutex_lock(&count_mutex); --threadcount; if (threadcount == 0) exit(0); pthread_mutex_unlock(&count_mutex); return 0; } if (sscanf(inbuf, "%dd%d", &dice, &size) != 2) { fprintf(s->out, "Sorry, but I couldn't understand that.\\n"); } else { int i; int total = 0; for (i = 0; i < dice; ++i) { int x = roll_die(size); total += x; fprintf(s->out, "%d ", x); fflush(s->out); if (do_sleep) sleep(1); } fprintf(s->out, "= %d\\n", total); } } return 0; } int main(int argc, char *argv[]) { int o; int sock; while ((o = getopt(argc, argv, "dstS")) != -1) { switch (o) { case 'S': do_sleep = 1; break; case 'd': do_debug = 1; break; case 's': do_stdin = 1; break; case 't': do_thread = 1; break; } } if (do_thread) { pthread_mutex_init(&count_mutex, 0); pthread_mutex_init(&rand_mutex, 0); } if (do_stdin) { struct sockets s; s.local = 1; s.in = stdin; s.out = stdout; if (do_thread) { spawn(&s); } else { roll_dice(&s); exit(0); } } sock = socket_setup(); while (1) { struct sockets *s = get_sockets(sock); if (s) { if (do_thread) { spawn(s); } else { roll_dice(s); exit(0); } } } return 0; } int socket_setup(void) { struct protoent *tcp_proto; struct sockaddr_in local; int r, s, one; tcp_proto = getprotobyname("tcp"); if (!tcp_proto) { fail("Can't find TCP/IP protocol: %s\\n", strerror(errno)); } s = socket(PF_INET, SOCK_STREAM, tcp_proto->p_proto); if (s == -1) { fail("socket: %s\\n", strerror(errno)); } one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_family = AF_INET; local.sin_port = htons(6173); r = bind(s, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (r == -1) { fail("bind: %s\\n", strerror(errno)); } r = listen(s, 5); if (r == -1) { fail("listen: %s\\n", strerror(errno)); } return s; } struct sockets * get_sockets(int sock) { int conn; if ((conn = accept(sock, 0, 0)) < 0) { warn("accept: %s\\n", strerror(errno)); return 0; } else { struct sockets *s; s = malloc(sizeof(struct sockets)); if (s == 0) { warn("malloc failed.\\n"); return 0; } s->local = 0; s->in = fdopen(conn, "r"); s->out = fdopen(conn, "w"); setlinebuf(s->in); setlinebuf(s->out); return s; } } void spawn(struct sockets *s) { pthread_t p; pthread_mutex_lock(&count_mutex); pthread_create(&p, 0, roll_dice, (void *) s); ++threadcount; pthread_mutex_unlock(&count_mutex); }
0
#include <pthread.h> pthread_mutex_t lock; struct serverParm{ int connectionDesc; }; char* concat(const char* s1, const char* s2){ char* result = malloc(strlen(s1)+strlen(s2)+1); strcpy(result, s1); strcat(result, s2); return result; } static int callback(void *data, int argc, char *argv[], char *azColName[]){ char** returnMsg; returnMsg = (char**)data; for(int i = 0; i < argc; i++){ *returnMsg = concat(*returnMsg, azColName[i]); *returnMsg = concat(*returnMsg, " = "); *returnMsg = concat(*returnMsg, argv[i] ? argv[i] : 0); *returnMsg = concat(*returnMsg, "\\n"); } *returnMsg = concat(*returnMsg, "\\n"); return 0; } void *serverThread(void *parmPtr){ sqlite3 *db; if(sqlite3_open("book.db",&db)){ fprintf(stderr, "SERVER: Can't open database %s\\n", sqlite3_errmsg(db)); return 0; } else{ fprintf(stdout, "SERVER: Opened databse successfully\\n"); } int recievedMsgLen, rc=0; char messageBuf[1024],*zErrMsg = 0; printf("DEBUG: connection made, connectionDesc=%d\\n", ((struct serverParm *) parmPtr)->connectionDesc); if(((struct serverParm *) parmPtr)->connectionDesc < 0){ printf("Accept failed\\n"); return(0); } while((recievedMsgLen=read(((struct serverParm *) parmPtr)->connectionDesc,messageBuf,sizeof(messageBuf)-1)) > 0){ char* data = ""; recievedMsgLen[messageBuf] = '\\0'; pthread_mutex_lock(&lock); rc = sqlite3_exec(db, messageBuf, callback, (void*)&data, &zErrMsg); if(rc != SQLITE_OK){ fprintf(stderr, "SERVER: SQL error: %s\\n", zErrMsg); sqlite3_free(zErrMsg); } else{ fprintf(stdout, "SERVER: Operation done successfully\\n"); } pthread_mutex_unlock(&lock); if(write(((struct serverParm *) parmPtr)->connectionDesc, data, 1024) < 0){ perror("SERVER: write error"); return 0; } if(strcmp(data,"") != 0) free(data); fprintf(stdout, "\\nSERVER: Waiting\\n"); } close(((struct serverParm *) parmPtr)->connectionDesc); free(((struct serverParm *) parmPtr)); return(0); } int main(int argc, char* argv[]){ int listenDesc, PORTNUMBER; struct sockaddr_in myAddr; struct serverParm *parmPtr; int connectionDesc; pthread_t threadID; if(argc != 2){ perror("Usage: TCPServer <Portnumber>"); exit(1); } PORTNUMBER = atoi(argv[1]); alarm(360); if(pthread_mutex_init(&lock,0) != 0){ printf("\\nSERVER: mutex init failed\\n"); return 1; } if((listenDesc = socket(AF_INET, SOCK_STREAM, 0)) < 0){ perror("open error on socket"); exit(1); } myAddr.sin_family = AF_INET; myAddr.sin_addr.s_addr = INADDR_ANY; myAddr.sin_port = htons(PORTNUMBER); if(bind(listenDesc, (struct sockaddr *) &myAddr, sizeof(myAddr)) < 0){ perror("bind error"); exit(1); } listen(listenDesc,5); while(1){ connectionDesc = accept(listenDesc, 0,0); parmPtr = (struct serverParm *)malloc(sizeof(struct serverParm)); parmPtr-> connectionDesc = connectionDesc; if(pthread_create(&threadID, 0, serverThread, (void*)parmPtr) != 0){ perror("Thread create error"); close(connectionDesc); close(listenDesc); exit(1); } printf("Parent ready for another connection\\n"); } pthread_mutex_destroy(&lock); }
1
#include <pthread.h> void *ocurrencias (void *arg); void imprimir(); pthread_mutex_t mutex; int *numOcurrencias; char **palabrasABuscar; int nPalabrasABuscar; int contador=0; int main(int argc, char **argv) { char *ruta = argv[1]; int nHilos = atoi(argv[2]); nPalabrasABuscar = argc-3; palabrasABuscar = recolectarPalabras(argc-3,argv); int numLineas = numero_lineas(ruta,0); int *numCaracteresXLinea = malloc(numLineas*sizeof(int)); numero_lineas(ruta,numCaracteresXLinea); int totalCaracteres = getTotalCaracteresArchivo(numLineas,numCaracteresXLinea); int tamanoParticion = totalCaracteres / nHilos; char **archivoDividido = dividirArchivo(ruta,nHilos,tamanoParticion); numOcurrencias = malloc(nPalabrasABuscar*sizeof(int)); for( int i=0 ; i<nPalabrasABuscar ; i++){ *(numOcurrencias+i) = 0; } pthread_t *hilos = malloc( nHilos * sizeof(pthread_t)); pthread_mutex_init(&mutex,0); for( int i = 0; i < nHilos ; i++ ) { int status = pthread_create(hilos+i, 0, ocurrencias, (void *)*(archivoDividido+i)); if (status < 0) { fprintf(stderr, "Error al crear el hilo\\n"); exit(-1); } pthread_join(*(hilos+i),0); } return 0; } void *ocurrencias (void *arg) { char *texto = (char*) arg; pthread_mutex_lock(&mutex); for( int i = 0; i < nPalabrasABuscar ; i++ ) contarOcurrencias(palabrasABuscar,texto,numOcurrencias,nPalabrasABuscar); imprimir(); pthread_mutex_unlock(&mutex); return (void *) 0; } void imprimir(){ contador += 1; printf("-------------------------------------------------%i\\n",contador); for( int i = 0; i < nPalabrasABuscar ; i++ ) { printf("Palabra: %s - Ocurrencias: %i\\n",*(palabrasABuscar+i),*(numOcurrencias+i)); } printf("-------------------------------------------------\\n"); }
0
#include <pthread.h> pthread_t tid[28], tid_read; char shared_var; pthread_mutex_t cond_var_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; int sequence, orig_sequence; FILE *fp; void *thread_write(void *arg) { pthread_mutex_lock(&cond_var_lock); int i = 0; pthread_t id; id = pthread_self(); while (1) { if (id == tid[i]) { while (i != sequence) { pthread_cond_wait(&cond_var, &cond_var_lock); } sequence++; orig_sequence = sequence; sequence = -1; if (i == 26) shared_var = '\\n'; else shared_var = 65 + i; pthread_cond_broadcast(&cond_var); pthread_mutex_unlock(&cond_var_lock); pthread_exit(0); } i++; if (i == 27) i = 0; } } void *thread_read(void *arg) { int count = 27; char read_var; while (count) { pthread_mutex_lock(&cond_var_lock); while (sequence >= 0) { pthread_cond_wait(&cond_var, &cond_var_lock); } read_var = shared_var; fwrite(&read_var, 1, 1, fp); sequence = orig_sequence; pthread_cond_broadcast(&cond_var); pthread_mutex_unlock(&cond_var_lock); count--; } } int main(int argc, char **argv) { int i, ret, repeat = 10; if (argc != 2) { printf("Invalid argument.\\n"); return -1; } fp = fopen(argv[1], "w"); if (fp == 0) { perror("fopen:"); return -1; } while (repeat) { for (i = 0; i < 27; i++) { ret = pthread_create((&tid[i]), 0, &thread_write, 0); if (ret != 0) { printf("error creating thread.\\n"); return; } } ret = pthread_create(&tid[27], 0, &thread_read, 0); if (ret != 0) { printf("error creating thread.\\n"); return -1; } for (i = 0; i < 28; i++) { pthread_join(tid[i], 0); } repeat--; sequence = 0; } return 0; }
1
#include <pthread.h> int *all_buffers; int num_producers; int num_consumers; int num_buffers; int num_items; int num_producer_iterations; int actual_num_produced; pthread_mutex_t should_continue_producing_lock; pthread_mutex_t buffer_printer_lock; sem_t *total_empty; sem_t *total_full; sem_t *buffer_lock; bool shouldContinueProducing() { if (num_producer_iterations <= num_items) { num_producer_iterations++; return 1; } else { return 0; } } void bufferPrinter(int thread_number) { if (actual_num_produced % 1000 == 0 && actual_num_produced != 0) { printf("%d items created\\n", actual_num_produced); int i; sem_wait(buffer_lock); for (i = 0; i < num_buffers; i++) { printf("Shared buffer %d has %d number of items\\n", i + 1, all_buffers[i]); } sem_post(buffer_lock); } actual_num_produced++; return; } void *producer(void *t_number) { int thread_number = *((int *) t_number); while (1) { pthread_mutex_lock(&should_continue_producing_lock); bool shouldContinue = shouldContinueProducing(); pthread_mutex_unlock(&should_continue_producing_lock); if (shouldContinue == 0) { break; } sem_wait(total_empty); sem_wait(buffer_lock); int i; for (i = 0; i < num_buffers; i++) { if (all_buffers[i] < 1024) { all_buffers[i]++; break; } } sem_post(buffer_lock); sem_post(total_full); pthread_mutex_lock(&buffer_printer_lock); bufferPrinter(thread_number); pthread_mutex_unlock(&buffer_printer_lock); } } void main(int argc, char *argv[]) { if (argc != 5) { printf("Wrong number of arguments...Exiting\\n"); return; } num_producers = atoi(argv[1]); num_consumers = atoi(argv[2]); num_buffers = atoi(argv[3]); num_items = atoi(argv[4]); num_producer_iterations = 0; actual_num_produced = 0; int *mapped_memory; int mapped_memory_size = num_buffers * sizeof(int); const char *filename = "/tmp/mapped_memory_bufferfile.txt"; int file_descriptor = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (file_descriptor < 0) { printf("ERROR: Couldn't create a buffer file! Exiting..."); exit(1); } mapped_memory = (int*)mmap(0, mapped_memory_size, PROT_WRITE, MAP_SHARED, file_descriptor, 0); close(file_descriptor); all_buffers = mapped_memory; total_full = sem_open(FULL_SEMAPHORE_NAME, 0); total_empty = sem_open(EMPTY_SEMAPHORE_NAME, 0); buffer_lock = sem_open(BUFFER_SEMAPHORE_NAME, 0); pthread_mutex_init(&should_continue_producing_lock, 0); pthread_mutex_init(&buffer_printer_lock, 0); printf("Num producers: %d, Num Conusumers: %d," " Num Buffers: %d, Num Items: %d\\n", num_producers, num_consumers, num_buffers, num_items); pthread_t *producer_threads = (pthread_t *) malloc(num_producers * sizeof(pthread_t)); int *producer_counters = (int *) malloc(num_producers * sizeof(int)); int counter; for (counter = 0; counter < num_producers; ++counter) { producer_counters[counter] = counter; } for (counter = 0; counter < num_producers; ++counter) { printf("Creating producer thread %d\\n", counter); pthread_create(&producer_threads[counter], 0, producer, (void *) &producer_counters[counter]); } for (counter = 0; counter < num_producers; ++counter) { pthread_join(producer_threads[counter], 0); } }
0
#include <pthread.h> int NO_READERS; int NO_WRITERS; int NO_READERS_READING = 0; bool VERBOSE; pthread_mutex_t resourceMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t readerMutex = PTHREAD_MUTEX_INITIALIZER; void *readerJob(void *arg) { while (1) { pthread_mutex_lock(&readerMutex); NO_READERS_READING++; if (NO_READERS_READING == 1) { pthread_mutex_lock(&resourceMutex); } pthread_mutex_unlock(&readerMutex); readMemory((int) (uintptr_t) arg, SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE); pthread_mutex_lock(&readerMutex); NO_READERS_READING--; if (NO_READERS_READING == 0) { pthread_mutex_unlock(&resourceMutex); } pthread_mutex_unlock(&readerMutex); } return 0; } void *writerJob(void *arg) { while (1) { pthread_mutex_lock(&resourceMutex); writeMemory(SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE); pthread_mutex_unlock(&resourceMutex); } return 0; } int main(int argc, char *argv[]) { parseArguments(argc, argv, 2, &NO_READERS, &NO_WRITERS, &VERBOSE); printf("Readers–writers problem: readers-preference (writers may starve) with mutex synchronization.\\n"); printf(" NO_READERS=%i, NO_WRITERS=%i, VERBOSE=%i\\n\\n", NO_READERS, NO_WRITERS, VERBOSE); pthread_t *readersThreadsIds = malloc(NO_READERS * sizeof(pthread_t)); if (readersThreadsIds == 0) { cannotAllocateMemoryError(); } pthread_t *writersThreadsIds = malloc(NO_READERS * sizeof(pthread_t)); if (writersThreadsIds == 0) { cannotAllocateMemoryError(); } srand(time(0)); initSharedArray(); for (int i = 0; i < NO_READERS; ++i) { if (pthread_create(&readersThreadsIds[i], 0, readerJob, (void *) (uintptr_t) i) != 0) { throwError("pthread_create error"); } } for (int i = 0; i < NO_WRITERS; ++i) { if (pthread_create(&writersThreadsIds[i], 0, writerJob, 0) != 0) { throwError("pthread_create error"); } } for (int i = 0; i < NO_READERS; ++i) { if (pthread_join(readersThreadsIds[i], 0) != 0) { throwError("pthread_join error"); } } for (int i = 0; i < NO_WRITERS; ++i) { if (pthread_join(writersThreadsIds[i], 0) != 0) { throwError("pthread_join error"); } } free(readersThreadsIds); free(writersThreadsIds); pthread_mutex_destroy(&resourceMutex); pthread_mutex_destroy(&readerMutex); return 0; }
1
#include <pthread.h>static char *rcs_file_verson = "$Id: pgen.c,v 1.3 2013/12/02 19:16:57 chuck Exp $"; uint64_t LastP; int DeltaP; PgenInit( Threads ) int Threads; { int i,j; uint64_t *P; primegen_init(&PG); if (Threads < 1 || Threads > (MAXTHREADS-1)) return (-1); for (i=0; i<MAXTHREADS; i++) Lowtide[i] = Hightide[i] = 0; PgenNumThreads = Threads; return (Threads); } int PgenSkipto(uint64_t Skipto) { pthread_mutex_lock(&PgenLock); primegen_skipto(&PG, Skipto); pthread_mutex_unlock(&PgenLock); } int PgenPause() { pthread_mutex_lock(&PgenLock); } int PgenResume() { pthread_mutex_unlock(&PgenLock); } int PgenDone(int Tid) { Lowtide[Tid] = Hightide[Tid]; return; } uint64_t PgenNext(int Tid) { register uint64_t P; Lowtide[Tid] = Hightide[Tid]; pthread_mutex_lock(&PgenLock); Hightide[Tid] = P = primegen_next(&PG); DeltaP++; pthread_mutex_unlock(&PgenLock); return (P); } uint64_t PgenLowtide() { uint64_t tide = SIEVELIMIT; int i; for (i=0; i<MAXTHREADS; i++) if (Lowtide[i] && (Lowtide[i] < tide)) tide = Lowtide[i]; LastP = tide; return tide; }
0
#include <pthread.h> int sala_espera = 0; int elfos_dudosos = 0; pthread_mutex_t santa_duerme = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t santa_libre = PTHREAD_COND_INITIALIZER; pthread_cond_t sala_espera_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t sala_espera_m = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t elfos_dudosos_m = PTHREAD_MUTEX_INITIALIZER; void *llegada_reno(void *param) { while (1) { sleep(1 * random() % 5); pthread_mutex_lock(&santa_duerme); pthread_mutex_lock(&sala_espera_m); if (sala_espera < 9) { sala_espera++; printf("Llega reno... Total: %d\\n", sala_espera); if (sala_espera == 9) { pthread_mutex_unlock(&sala_espera_m); printf("todos renos, repartimos!\\n"); pthread_cond_signal(&santa_libre); pthread_cond_wait(&sala_espera_cond, &santa_duerme); } else { pthread_mutex_unlock(&sala_espera_m); pthread_cond_wait(&sala_espera_cond, &santa_duerme); } } else { pthread_mutex_unlock(&sala_espera_m); } pthread_mutex_unlock(&santa_duerme); } } void elfo_duda() { while (1) { sleep(1 * random() % 5); pthread_mutex_lock(&santa_duerme); pthread_mutex_lock(&elfos_dudosos_m); elfos_dudosos++; printf("Llega elfo.. Total: %d\\n", elfos_dudosos); if (elfos_dudosos >= 3) { pthread_mutex_unlock(&elfos_dudosos_m); printf("todos elfos, santa llamado!\\n"); pthread_cond_signal(&santa_libre); pthread_cond_wait(&sala_espera_cond, &santa_duerme); } else { pthread_mutex_unlock(&elfos_dudosos_m); pthread_cond_wait(&sala_espera_cond, &santa_duerme); } pthread_mutex_unlock(&santa_duerme); } } void repartir_regalos() { pthread_mutex_lock(&sala_espera_m); sala_espera = 0; pthread_mutex_unlock(&sala_espera_m); printf("repartiendo regalos. Ahora hay %d renos\\n", sala_espera); sleep(1 * random() % 5); printf("regalos repartidos!\\n"); pthread_cond_broadcast(&sala_espera_cond); } void resolver_dudas() { pthread_mutex_lock(&elfos_dudosos_m); elfos_dudosos = elfos_dudosos - 3; printf("resolviendo dudas, ahora hay %d elfos\\n", elfos_dudosos); pthread_mutex_unlock(&elfos_dudosos_m); sleep(1 * random() % 5); printf("dudas contestadas!\\n"); pthread_cond_broadcast(&sala_espera_cond); } void santa() { while (1) { pthread_mutex_lock(&santa_duerme); printf("santa duerme\\n"); while ((sala_espera < 9) && (elfos_dudosos < 3)) { pthread_cond_wait(&santa_libre, &santa_duerme); } printf("santa se despierta!\\n"); pthread_mutex_lock(&elfos_dudosos_m); pthread_mutex_lock(&sala_espera_m); if (sala_espera >= 9) { pthread_mutex_unlock(&elfos_dudosos_m); pthread_mutex_unlock(&sala_espera_m); repartir_regalos(); } else if (elfos_dudosos >= 3) { pthread_mutex_unlock(&elfos_dudosos_m); pthread_mutex_unlock(&sala_espera_m); resolver_dudas(); } pthread_mutex_unlock(&santa_duerme); } } int main() { int i; pthread_t renos[9]; pthread_t elfos[3]; pthread_t santa_t; pthread_create(&santa_t, 0, (void *) &santa, 0); for (i = 0; i < 9; i++) { pthread_create(&renos[i], 0, (void *) &llegada_reno, 0); } for (i = 0; i < 3; i++) { pthread_create(&elfos[i], 0, (void *) &elfo_duda, 0); } for (i = 0; i < 9; i++) { pthread_join(renos[i], 0); } for (i = 0; i < 3; i++) { pthread_join(elfos[i], 0); } pthread_join(santa_t, 0); pthread_mutex_destroy(&santa_duerme); return 0; }
1
#include <pthread.h> int pile[2]; int stack_size = -1; pthread_mutex_t mutex_stack = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_pop = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_push = PTHREAD_COND_INITIALIZER; void push(int car) { pthread_mutex_lock(&mutex_stack); while (stack_size == 2){ printf("%ld | -> Attente consommateur\\n", (long ) pthread_self()); pthread_cond_wait(&cond_pop,&mutex_stack); } stack_size++; pile[stack_size] = car ; if((int)car == 10) printf("%ld | Empilation du caractère de fin\\n",(long ) pthread_self()); else printf("%ld | Empilation de : %c\\n",(long ) pthread_self(), pile[stack_size]); if (stack_size == 0){ printf("%ld | Réveil du consommateur \\n", (long ) pthread_self()); pthread_cond_signal(&cond_push); } pthread_mutex_unlock(&mutex_stack); } int pop(){ int car; pthread_mutex_lock(&mutex_stack); while (stack_size == -1){ printf("%ld | Le consommateur s'endort\\n", (long ) pthread_self()); pthread_cond_wait(&cond_push,&mutex_stack); } car = pile[stack_size]; stack_size --; if((int)car == 10) printf("%ld | Dépilation du caractère de fin\\n",(long ) pthread_self()); else printf("%ld | Dépilation de : %c\\n",(long ) pthread_self(),car); if (stack_size == (2 -1)){ printf("%ld | Réveil du producteur\\n",(long ) pthread_self()); pthread_cond_signal(&cond_pop); } pthread_mutex_unlock(&mutex_stack); return car; } void *producteur() { int c; while((c = getchar()) != EOF) { push(c); } pthread_exit ((void*)0); } void *consommateur() { while(1) { pop(); fflush(stdout); } pthread_exit ((void*)0); } int main (int argc, char* argv[]) { int *status; pthread_t pth1, pth2; stack_size = -1; if (pthread_create (&pth1, 0, producteur, (void*)0) != 0) { perror("pthread_create \\n"); exit (1); } if (pthread_create (&pth2, 0, consommateur, (void*)0) != 0) { perror("pthread_create \\n"); exit (1); } if (pthread_join(pth1, (void**) &status) != 0) { printf ("pthread_join"); exit (1); } if (pthread_join(pth2, (void**) &status) != 0) { printf ("pthread_join"); exit (1); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; int total = 0; int arrayA[16]; int arrayB[16]; void generate_values(){ for (int i = 0; i < 16; ++i){ arrayA[i] = rand() % 10; arrayB[i] = rand() % 10; } } void print(int *array, char * name, int array_size){ printf("%s = ", name); for (int i = 0; i < array_size; ++i){ if(i > 0) printf(", "); printf("%d", array[i]); } printf("\\n"); } void *Process(void *arg) { int thread_number = *(int *) arg; int block_size = 16 / 4; int parcial_sum = 0; int offset = (thread_number-1) * block_size; for (int i = 0; i < block_size; ++i){ parcial_sum += (arrayA[i+offset] * arrayB[i+offset]); } printf("Thread %d calculou de %d a %d: produto escalar parcial = %d\\n", thread_number, offset, offset+block_size-1, parcial_sum); pthread_mutex_lock(&mutex); total += parcial_sum; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char **argv){ printf("\\nGrupo: Cleverson de Oliveira Silva, Hery Victor\\n\\n"); pthread_mutex_init(&mutex, 0); pthread_t threads[4]; srand(time(0)); generate_values(); total = 0; print(arrayA, "A", 16); print(arrayB, "B", 16); for (int i = 0; i < 4; ++i){ int thread_number = i+1; pthread_create(&threads[i], 0, Process, (void *)&thread_number); } for (int i = 0; i < 4; ++i){ pthread_join(threads[i], 0); } printf("Produto escalar: %d\\n", total); pthread_mutex_destroy(&mutex); pthread_exit(0); }
1
#include <pthread.h> void *do_work_one(); void *do_work_two(); pthread_mutex_t first_mutex; pthread_mutex_t second_mutex; main() { pthread_t tid; int return_val; pthread_mutex_init(&first_mutex, 0); pthread_mutex_init(&second_mutex, 0); pthread_create(&tid, (pthread_attr_t *)0, (void *(*)())do_work_one, (void *)0); pthread_create(&tid, (pthread_attr_t *)0, (void *(*)())do_work_two, (void *)0); pthread_join(tid, (void **)0); printf("Mission Completed!\\n"); } void *do_work_one(void *param) { printf("Thread_one wants to acquire the first_mutex\\n"); pthread_mutex_lock(&first_mutex); printf("Thread_one acquired the first_mutex\\n"); sleep(1); printf("Thread_one wants to acquire the second_mutex\\n"); pthread_mutex_lock(&second_mutex); printf("Thread_one acquired the second_mutex\\n"); printf("Do some work...\\n"); pthread_mutex_unlock(&second_mutex); printf("Thread_one released the second_mutex\\n"); pthread_mutex_unlock(&first_mutex); printf("Thread_one released the first_mutex\\n"); pthread_exit(0); } void *do_work_two(void *param) { printf("Thread_one wants to acquire the first_mutex\\n"); pthread_mutex_lock(&second_mutex); printf("Thread_one acquired the first_mutex\\n"); sleep(1); printf("Thread_one wants to acquire the second_mutex\\n"); pthread_mutex_lock(&first_mutex); printf("Thread_one acquired the second_mutex\\n"); printf("Do some work...\\n"); pthread_mutex_unlock(&first_mutex); printf("Thread_one released the second_mutex\\n"); pthread_mutex_unlock(&second_mutex); printf("Thread_one released the first_mutex\\n"); pthread_exit(0); }
0
#include <pthread.h> pthread_mutexattr_t mutex_shared_attr; pthread_condattr_t cond_shared_attr; pthread_mutex_t *lock; pthread_cond_t *cond; int *bufferFull; struct timespec *start; int main(int argc, char **argv){ int size; if(argc < 2 || argc > 3){ fprintf(stderr, "Usage %s <buffersize>\\n", argv[0]); exit(0); } else{ size = atoi(argv[1]); } int returnVal; char* sharedMemory = (char *)mmap(0, size, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0); lock = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0); cond = (pthread_cond_t *)mmap(0, sizeof(pthread_cond_t), PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0); bufferFull = (int *)mmap(0, sizeof(int), PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0); *bufferFull = 0; start = (struct timespec *)mmap(0, sizeof(struct timespec), PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if((returnVal = pthread_mutexattr_init(&mutex_shared_attr)) != 0){ fprintf(stderr, "pthread_mutexattr_init"); return 1; } if((returnVal = pthread_mutexattr_setpshared(&mutex_shared_attr, PTHREAD_PROCESS_SHARED)) != 0){ fprintf(stderr, "pthread_mutexattr_setshared"); return 1; } if((returnVal = pthread_mutex_init(lock, &mutex_shared_attr)) != 0){ fprintf(stderr, "pthread_mutex_init"); return 1; } if((returnVal = pthread_condattr_init(&cond_shared_attr)) != 0){ fprintf(stderr, "pthread_condattr_init"); return 1; } if((returnVal = pthread_condattr_setpshared(&cond_shared_attr, PTHREAD_PROCESS_SHARED)) != 0){ fprintf(stderr, "pthread_condattr_setshared"); return 1; } if((returnVal = pthread_cond_init(cond, &cond_shared_attr)) != 0){ fprintf(stderr, "pthread_cond_init"); return 1; } int pid; switch(pid = fork()){ case 0: handleChild(&sharedMemory, size); break; case -1: perror("fork"); break; default: handleParent(&sharedMemory, size); break; } return 0; } void handleChild(char **sharedMemory, int size){ void *data = malloc(size); pthread_mutex_lock(lock); while(*bufferFull == 1){ pthread_cond_wait(cond, lock); } clock_gettime(CLOCK_REALTIME, start); memcpy(*sharedMemory, data, size); *bufferFull = 1; pthread_cond_signal(cond); pthread_mutex_unlock(lock); } void handleParent(char **sharedMemory, int size){ void *data = malloc(size); struct timespec stop; pthread_mutex_lock(lock); while(*bufferFull == 0){ pthread_cond_wait(cond, lock); } *bufferFull = 0; clock_gettime(CLOCK_REALTIME, &stop); pthread_cond_signal(cond); pthread_mutex_unlock(lock); long startnanoseconds = start->tv_sec * 1000000000 + start->tv_nsec; long stopnanoseconds = stop.tv_sec * 1000000000 + stop.tv_nsec; printf("%lu\\n", stopnanoseconds - startnanoseconds); }
1
#include <pthread.h> int *nbFichierRestant, *nbFichierMax; pthread_t* tabThread; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *funcThread(void *arg){ int *t = 0; t = malloc(sizeof(int)); char ** arguments = (char**)arg; pthread_mutex_lock(&mutex); while (*nbFichierRestant>2) { printf("Thread : %ld - Traitement du fichier : %s\\n",(long)pthread_self(),arguments[*nbFichierMax - *nbFichierRestant+2]); *nbFichierRestant = *nbFichierRestant - 1; pthread_mutex_unlock(&mutex); *t = upper(arguments[(*nbFichierMax - *nbFichierRestant)+1]); pthread_mutex_lock(&mutex); printf("Thread : %ld - Fin traitement valeur de t: %d\\n",(long)pthread_self(),*t); if(*t!=0){ pthread_mutex_unlock(&mutex); printf("Thread : %ld - fin du Thread\\n",(long)pthread_self()); pthread_exit((void*)arguments[(*nbFichierMax - *nbFichierRestant)+1]); } } printf("Thread : %ld - fin du Thread correct\\n",(long)pthread_self()); *t = 0; pthread_mutex_unlock(&mutex); pthread_exit((void*)t); } int main(int argc, char *argv[]) { int i; if(argc < 2) return 1; tabThread = malloc((argc-1)*sizeof(pthread_t)); nbFichierMax = malloc((argc-1)*sizeof(int)); nbFichierRestant = malloc((argc-1)*sizeof(int)); *nbFichierMax = *nbFichierRestant = argc; for (i = 0;i<atoi(argv[1]);i++) { pthread_create(&tabThread[i], 0, funcThread, (void *)argv); printf("thread %d\\n",i); } void *valRet = 0; int valRetour = 0; for (i = 0;i<atoi(argv[1]);i++) { pthread_join(tabThread[i], (void**)&valRet); if((*(int*)valRet) != 0){ printf("Le fichier %s pb \\n",(char*)valRet); valRetour++; } } return valRetour; }
0
#include <pthread.h> short isfst_oprd; short * isfst_done; char oprt; char * expr; int * rst; }expr_data; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int parse_expr( char expr[] ); void critical_section( expr_data * arg, int rst); void * thread_calc( void * arg ); void * thread_calc( void * arg ) { int rst = parse_expr( ((expr_data *)arg)->expr ); pthread_mutex_lock( &mutex ); critical_section( (expr_data *)arg, rst ); pthread_mutex_unlock( &mutex ); pthread_exit( 0 ); return 0; } void critical_section( expr_data * arg, int rst) { int tmp_rst = *(arg->rst); if (arg->oprt == '+') { *(arg->rst) = tmp_rst + rst; printf( "THREAD %u: Adding '%d'\\n", (unsigned int)pthread_self(), rst ); } else if (arg->oprt == '-') { if (arg->isfst_oprd == 1) { *(arg->rst) = tmp_rst + rst; printf( "THREAD %u: '%d' is subtracted \\n", (unsigned int)pthread_self(), rst ); } else { *(arg->rst) = tmp_rst - rst; printf( "THREAD %u: Subtracting '%d'\\n", (unsigned int)pthread_self(), rst ); } } else if (arg->oprt == '*') { *(arg->rst) = tmp_rst * rst; printf( "THREAD %u: Multiplying by '%d'\\n", (unsigned int)pthread_self(), rst ); } else { if (arg->isfst_oprd == 1) { *(arg->rst) = rst; *(arg->isfst_done) = 1; printf( "THREAD %u: '%d' is divided\\n", (unsigned int)pthread_self(), rst ); } else { if (*(arg->isfst_done) == 0) { pthread_mutex_unlock( &mutex ); while (*(arg->isfst_done) == 0); pthread_mutex_lock( &mutex ); } *(arg->rst) = *(arg->rst)/rst; printf( "THREAD %u: Dividing by '%d'\\n", (unsigned int)pthread_self(), rst ); } } } int parse_expr( char expr[] ) { if ( expr[0] != '(') { int rst = atoi(expr); return rst; } else { char oprt; int oprd_count = 0; int i = 1, rc, j; pthread_t tid[ 100 ]; char * tmp_expr[ 100 ]; expr_data edata[ 100 ]; int tcount = 0; while ( expr[i] == ' ' ) i++; oprt = expr[i]; i++; if (oprt != '+' && oprt != '-' && oprt != '*' && oprt != '/') { printf("THREAD %u: ERROR: unknown '%c' operator\\n", (unsigned int)pthread_self(), oprt); exit(1); } printf("THREAD %u: Starting '%c' operation\\n", (unsigned int)pthread_self(), oprt); int * rst = (int *)malloc( sizeof( int ) ); short * isfst_done = (short *)malloc( sizeof( short ) ); *isfst_done = 0; if (oprt == '+' || oprt == '-') { *rst = 0; } else { *rst = 1; } int start_index, end_index; expr[strlen(expr)-1] = '\\0'; while ( expr[i] != '\\0') { while ( expr[i] == ' ' ) i++; start_index = i; if ( expr[i] != '(' ) { while ( expr[i] != ' ') { if ( expr[i] == '\\0') break; i++; } } else { int parentheses_count = 1; while ( parentheses_count != 0 ) { i++; if ( expr[i] == '(' ) parentheses_count += 1; if ( expr[i] == ')' ) parentheses_count -= 1; if ( expr[i] == '\\0') { printf("ERROR: Invalid expression\\n"); return 1; } } i++; } end_index = i; tmp_expr[tcount] = (char *)malloc( sizeof( char )*(end_index - start_index + 1) ); memcpy( tmp_expr[tcount], expr + start_index, end_index - start_index); tmp_expr[tcount][end_index - start_index] = '\\0'; if ( tcount == 0) { edata[tcount].isfst_oprd = 1; } else { edata[tcount].isfst_oprd = 0; } edata[tcount].isfst_done = isfst_done; edata[tcount].oprt = oprt; edata[tcount].expr = tmp_expr[tcount]; edata[tcount].rst = rst; rc = pthread_create( &tid[tcount], 0, thread_calc , &edata[tcount] ); tcount++; oprd_count++; if ( rc != 0 ) { perror( "Could not create the thread" ); } } for (j=0; j<tcount; j++) { rc = pthread_join( tid[j], 0 ); if (rc != 0) { printf("THREAD %u: child %u terminated with nonzero exit status %d", (unsigned int)pthread_self(), (unsigned int)tid[j], rc); exit(1); } free(tmp_expr[tcount]); } int result = *rst; free(rst); free(isfst_done); if ( oprd_count < 2 ) { printf("THREAD %u: ERROR: not enough operands\\n", (unsigned int)pthread_self()); exit(1); } printf( "THREAD %u: Ended '%c' operation with result '%d'\\n", (unsigned int)pthread_self(), oprt, result ); return result; } } int main( int argc, char* argv[]) { if (argc != 2) { printf("ERROR: Invalid arguments\\nUSAGE: ./a.out <input-file>\\n"); return 1; } int fd = open( argv[1], O_RDONLY ); if ( fd == -1 ) { perror( "open() failed\\n" ); return 1; } char expr_buf[100]; int rc = read(fd, expr_buf, sizeof(expr_buf)); if ( rc == -1 ) { perror("read() failed\\n"); return 1; } if ( expr_buf[rc-1] == '\\n' ) { expr_buf[rc-1] = '\\0'; } else { expr_buf[rc] = '\\0'; } int rst = parse_expr(expr_buf); printf("THREAD %u: Final answer is '%d'\\n", (unsigned int)pthread_self(), rst); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; int foo = 0; void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; int currvalue = sip->value; pthread_mutex_unlock(&(sip->lock)); printf("Current value was %i.\\n", currvalue); foo = currvalue; sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); if(sip->value+foo == 3 || sip->value+foo == 4) { return 0; } else { return 1; } }
0
#include <pthread.h> pthread_mutex_t fifo_mut; pthread_cond_t fifo_cond; void fifo_lock() { pthread_mutex_lock (&fifo_mut); } void fifo_unlock() { pthread_mutex_unlock (&fifo_mut); } void fifo_wait() { pthread_cond_wait (&fifo_cond, &fifo_mut); } void fifo_unlock_and_notify() { pthread_mutex_unlock (&fifo_mut); pthread_cond_signal (&fifo_cond); } void init_runtime() { pthread_mutex_init (&fifo_mut, 0); pthread_cond_init (&fifo_cond, 0); }
1
#include <pthread.h> int Buffer_Index_Value = 0; char *Buffer_Queue; pthread_mutex_t mutex_variable = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t Buffer_Queue_Not_Full = PTHREAD_COND_INITIALIZER; pthread_cond_t Buffer_Queue_Not_Empty = PTHREAD_COND_INITIALIZER; void *ping() { while(1) { pthread_mutex_lock(&mutex_variable); if(Buffer_Index_Value == -1) { pthread_cond_wait(&Buffer_Queue_Not_Empty, &mutex_variable); } sleep(1); Buffer_Index_Value--; printf("ping\\n"); pthread_mutex_unlock(&mutex_variable); pthread_cond_signal(&Buffer_Queue_Not_Full); sleep(1); } } void *pong() { usleep(1); while(1) { pthread_mutex_lock(&mutex_variable); if(Buffer_Index_Value == 10) { pthread_cond_wait(&Buffer_Queue_Not_Full, &mutex_variable); } Buffer_Index_Value++; sleep(1); printf("pong\\n"); pthread_mutex_unlock(&mutex_variable); pthread_cond_signal(&Buffer_Queue_Not_Empty); sleep(1); } } int main() { pthread_t pong_thread_id, ping_thread_id; Buffer_Queue = (char *) malloc(sizeof(char) * 10); pthread_create(&ping_thread_id, 0, ping, 0); pthread_create(&pong_thread_id, 0, pong, 0); pthread_join(pong_thread_id, 0); pthread_join(ping_thread_id, 0); return 0; }
0
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
1
#include <pthread.h> int q[3]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 3) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 3); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[8]; int sorted[8]; void producer () { int i, idx; for (i = 0; i < 8; i++) { idx = findmaxidx (source, 8); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 8); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 8; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 8); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 8; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t rec_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; void thr1_fun(void) { int rc; printf("start thr1_fun\\n"); rc = pthread_mutex_lock(&rec_mutex); if(rc) { perror("thr1_fun, pthread_mutex_lock"); pthread_exit(0); } printf("thr1_fun executing\\n"); rc = pthread_mutex_lock(&rec_mutex); if(rc) { perror("thr1_fun, pthread_mutex_lock 2"); pthread_exit(0); } printf("thr1_fun double lock and executing\\n"); pthread_mutex_unlock(&rec_mutex); sleep(1); printf("thr1_fun finished\\n"); pthread_mutex_unlock(&rec_mutex); } void thr2_fun(void) { int rc; printf("start thr2_fun\\n"); rc = pthread_mutex_lock(&rec_mutex); if(rc) { perror("thr1_fun, pthread_mutex_lock"); pthread_exit(0); } printf("thr2_fun executing\\n"); sleep(1); printf("thr2_fun finished\\n"); pthread_mutex_unlock(&rec_mutex); } int main(int argc, char* argv[]) { int thr_id1, thr_id2, rc; pthread_t p_thread1, p_thread2; thr_id1 = pthread_create(&p_thread1, 0, thr1_fun, 0); thr_id2 = pthread_create(&p_thread2, 0, thr2_fun, 0); sleep(4); printf("main end. \\n"); }
1
#include <pthread.h> struct person_info { int sex; char name[32 +1]; int age; }; pthread_mutex_t mutex; void *write_thread_routine(void * arg) { int i; char buf[1024]; struct person_info *pInfo = (struct person_info *)arg; printf("I'm sub thread,my thread ID is:0x%x\\n", (int)pthread_self()); if(!pInfo) { pthread_exit(0); } while (1) { fprintf (stderr, "writer: please input string:"); bzero (buf, 1024); if (fgets (buf, 1024 - 1, stdin) == 0) { perror ("fgets"); continue; } int len = strlen(buf); if(len > 32) { len = 32; } pthread_mutex_lock(&mutex); pInfo->sex = 1; pInfo->age = 18; bzero(pInfo->name, 32 +1); strncpy(pInfo->name, buf, len); pthread_mutex_unlock(&mutex); if ( !strncasecmp (buf, "quit", strlen ("quit"))) { break; } } pthread_exit((void *)pInfo); } void read_thread_routine(void *arg) { struct person_info *pInfo = (struct person_info *)arg; printf("I'm read thread!\\n"); if(!pInfo) { pthread_exit(0); } while(1) { pthread_mutex_lock(&mutex); if ( !strncasecmp (pInfo->name, "quit", strlen ("quit"))) { pthread_mutex_unlock(&mutex); break; } printf("read: sex = %d, age=%d, name=%s\\n", pInfo->sex, pInfo->age, pInfo->name); pthread_mutex_unlock(&mutex); usleep(200000); } pthread_exit(0); } int main(void) { pthread_t tid_w, tid_r; char *msg = "Hello, 1510"; struct person_info *pInfo = 0; printf("thread demo!\\n"); pInfo = (struct person_info *)malloc(sizeof(struct person_info)); if(!pInfo) { exit(1); } pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&mutex, &mutexattr); pthread_mutexattr_destroy(&mutexattr); pthread_create(&tid_w, 0, write_thread_routine, (void *)pInfo); pthread_create(&tid_r, 0, (void *)read_thread_routine, (void *)pInfo); pthread_join(tid_w, 0); pthread_join(tid_r, 0); pthread_mutex_destroy(&mutex); if(pInfo) free(pInfo); sleep(5); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void *conversion_func(void *arg) { char *nomF=(char*)(arg); int c; FILE* fp1, *fp2; c=1; pthread_mutex_lock(&mutex); fp1= fopen (nomF, "r"); fp2= fopen (nomF, "r+"); if ((fp1== 0) || (fp2== 0)) { perror ("fopen thread"); pthread_exit((void*)1); } while (c !=EOF) { c=fgetc(fp1); if (c!=EOF) fputc(toupper(c),fp2); } fclose (fp1); fclose (fp2); printf("Thread %d termine, le fichier '%s' a été convertit.\\n",(int)pthread_self(),nomF); pthread_mutex_unlock(&mutex); pthread_exit((void*)pthread_self()); } int main (int argc, char ** argv) { int nbrF=argc-1,i,status; pthread_t* tid; tid = (pthread_t *)malloc(nbrF*sizeof(pthread_t)); printf("nombre de fichiers à convertir : %d\\n",nbrF); for (i=0;i<nbrF;i++) { if (pthread_create(&tid[i],0,conversion_func,(void *)argv[i+1])!=0) { printf("ERREUR:creation\\n"); exit(1); } } for (i=0;i<nbrF;i++) { if (pthread_join(tid[i],(void **)&status)!=0) { printf("ERREUR:joindre\\n"); exit(2); } } printf("Tous les fichiers sont convertit.\\n"); return 0; }
1
#include <pthread.h> int cnt ; { int g_i ; pthread_mutex_t lock; }NODE, *pNODE ; void* thd_handle(void* arg) { pNODE p = (pNODE)arg ; int tmp ; while(1) { pthread_mutex_lock( &p ->lock); if(p ->g_i <= 0) { pthread_mutex_unlock(&p ->lock); sleep(rand() % 5 + 1); continue ; } tmp = p ->g_i ; sleep(rand()%3 + 1); printf("%u: sell a ticket: %d\\n",pthread_self(), tmp ); cnt ++ ; p->g_i -- ; pthread_mutex_unlock(&p ->lock); sleep(rand()%2 + 1); } } int main(int argc, char* argv[]) { NODE anode ; memset(&anode, 0, sizeof(anode)); anode.g_i = 10 ; pthread_t thd1, thd2, thd3 ; pthread_mutex_t mylock ; if(0 != pthread_mutex_init(&anode.lock, 0) ) { printf("mutex_init fail!\\n"); exit(1); } if(pthread_create(&thd1, 0, thd_handle, (void*)&anode ) != 0) { printf("pthread_create fail!\\n"); exit(-1); } if(pthread_create(&thd2, 0, thd_handle, (void*)&anode ) != 0) { printf("pthread_create fail!\\n"); exit(-1); } if(pthread_create(&thd3, 0, thd_handle, (void*)&anode ) != 0) { printf("pthread_create fail!\\n"); exit(-1); } while(1) { pthread_mutex_lock(&anode.lock); if(anode.g_i <= 0) { anode.g_i = 5 ; printf("ticket on!\\n"); } pthread_mutex_unlock(&anode.lock); } pthread_join(thd1, 0); pthread_join(thd2, 0); pthread_join(thd3, 0); pthread_mutex_destroy(&anode.lock); printf("cnt: %d\\n", cnt); return 0; }
0
#include <pthread.h> pthread_mutex_t locki[32]; int inode[32]; pthread_mutex_t lockb[26]; int busy[26]; void *thread(void* arg) { int i = (*(int*) arg) % 32; pthread_mutex_lock(locki + i); if (inode[i] == 0) { int b = (i * 2) % 26; while (1) { pthread_mutex_lock(lockb + b); if (!busy[b]) { busy[b] = 1; inode[i] = b + 1; pthread_mutex_unlock(lockb + b); break; } pthread_mutex_unlock(lockb + b); b = (b + 1) % 26; } } pthread_mutex_unlock(locki + i); pthread_exit(0); } void initialize_inodes() { for (int i = 0; i < 32; ++i) { pthread_mutex_init(locki + i, 0); } } void initialize_blocks() { for (int i = 0; i < 26; ++i) { pthread_mutex_init(lockb + i, 0); } } int main() { initialize_inodes(); initialize_blocks(); pthread_t threads[14]; int tids[14]; for (int i = 0; i < 14; ++i) { tids[i] = i; pthread_create(threads + i, 0, thread, tids + i); } for (int i = 0; i < 14; ++i) { pthread_join(threads[i], 0); } return(0); }
1
#include <pthread.h> static char envbuf[200]; char ** envrion; int pthread_exec_count; int g_index; pthread_mutex_t env_mutex; pthread_once_t init_done = PTHREAD_ONCE_INIT; void thread_init(void); int safe_getenv(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; envrion[i] != 0 ; i++) { if (strncmp(name, envrion[i], len) == 0 && (envrion[i][len] == '=')) { olen = strlen(&envrion[i][len + 1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return -1; } strcpy(buf, &envrion[i][len + 1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return -1; } 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); } char * getenv(const char * name) { int i, len; len = strlen(name); for (i = 0; envrion[i] != 0 ; i++) { if (strncmp(name, envrion[i], len) == 0 && (envrion[i][len] == '=')) { strcpy(envbuf, &envrion[i][len + 1]); return envbuf; } } return 0 ; } void * pthread_do(void * arg) { int t_i = 0; for (; t_i < pthread_exec_count; t_i++) { char * value = getenv("HOME"); printf("%d: value is %s\\n", g_index, value); g_index++; fflush(0 ); } return 0; } void * pthread_do2(void * arg) { int t_i = 0; for (; t_i < pthread_exec_count; t_i++) { char * value = getenv("SHELL"); printf("%d: value is %s\\n", g_index, value); g_index++; fflush(0 ); } return 0; } void * pthread_do3(void * arg) { int t_i = 0; for (; t_i < pthread_exec_count; t_i++) { char value[100]; int i = safe_getenv("HOME", value, 100); if (i >= 0) { printf("%d: value is %s\\n", g_index, value); g_index++; } else { printf("get error!\\n"); } fflush(0 ); } return 0; } void * pthread_do4(void * arg) { int t_i = 0; for (; t_i < pthread_exec_count; t_i++) { char value[100]; int i = safe_getenv("SHELL", value, 100); if (i >= 0) { printf("%d: value is %s\\n", g_index, value); g_index++; } else { printf("get error!\\n"); } fflush(0 ); } return 0; } int main2(int argc, char ** argv) { envrion = (char **) malloc(sizeof(char *) * 2); envrion[0] = "HOME=/home/testuser/haha"; envrion[1] = "SHELL=/shell"; envrion[2] = 0; pthread_exec_count = 200; g_index = 0; pthread_t t_1; pthread_t t_2; pthread_t t_3; pthread_t t_4; pthread_create(&t_1, 0, pthread_do, 0 ); pthread_create(&t_3, 0, pthread_do2, 0 ); pthread_create(&t_2, 0, pthread_do, 0 ); pthread_create(&t_4, 0, pthread_do2, 0 ); pthread_join(t_1, 0 ); pthread_join(t_2, 0 ); pthread_join(t_3, 0 ); pthread_join(t_4, 0 ); exit(0); } int main(int argc, char ** argv) { envrion = (char **) malloc(sizeof(char *) * 2); envrion[0] = "HOME=/home/testuser/haha"; envrion[1] = "SHELL=/shell"; envrion[2] = 0; pthread_exec_count = 200; g_index = 0; pthread_t t_1; pthread_t t_2; pthread_t t_3; pthread_t t_4; pthread_create(&t_1, 0, pthread_do3, 0 ); pthread_create(&t_3, 0, pthread_do4, 0 ); pthread_create(&t_2, 0, pthread_do3, 0 ); pthread_create(&t_4, 0, pthread_do4, 0 ); pthread_join(t_1, 0 ); pthread_join(t_2, 0 ); pthread_join(t_3, 0 ); pthread_join(t_4, 0 ); exit(0); }
0
#include <pthread.h> pthread_t tid[4]; pthread_mutex_t mutex; int *array; int length = 100; int count = 0; int double_count = 0; int t = 4; int max_threads = 0; struct padded_int { int value; char padding[60]; }; struct padded_int private_count[4]; void *count3s_thread(void *arg) { int i; int length_per_thread = length/max_threads; int id = *((int*)(arg)); int start = id * length_per_thread; printf("\\tThread [%d] starts [%d] length [%d]\\n",id, start, length_per_thread); for (i = start; i < start + length_per_thread; i++) { if (array[i] == 3) { private_count[id].value++; } } pthread_mutex_lock(&mutex); count += private_count[id].value; pthread_mutex_unlock(&mutex); } void initialize_vector() { int i = 0; array = (int*) malloc(sizeof(int) * 100); if (array == 0) { printf("Allocation memory failed!\\n"); exit(-1); } for (; i < 100; i++) { array[i] = rand() % 20; if (array[i] == 3) double_count++; } } int main(int argc, char *argv[]) { int i = 0; int err; clock_t t1, t2; if (argc == 2) { max_threads = atoi(argv[1]); if (max_threads > 4) max_threads = 4; } else { max_threads = 4; } printf("[fourthSolution] Using %d threads\\n",max_threads); srand(time(0)); printf("*** fourthSolution ***\\n"); printf("Initializing vector... "); fflush(stdout); initialize_vector(); printf("Vector initialized!\\n"); fflush(stdout); t1 = clock(); pthread_mutex_init(&mutex,0); while (i < max_threads) { private_count[i].value = 0; err = pthread_create(&tid[i], 0, &count3s_thread, &i); if (err != 0) printf("[fourthSolution] Can't create a thread: [%d]\\n", i); else printf("[fourthSolution] Thread created!\\n"); i++; } i = 0; for (; i < max_threads; i++) { void *status; int rc; rc = pthread_join(tid[i], &status); if (rc) { printf("ERROR; retrun code from pthread_join() is %d\\n", rc); exit(-1); } else { printf("Thread [%d] exited with status [%ld]\\n", i, (long)status); } } printf("[fourthSolution] Count by threads %d\\n", count); printf("[fourthSolution] Double check %d\\n", double_count); pthread_mutex_destroy(&mutex); t2 = clock(); printf("[[fourthSolution] Elapsed time %f\\n", (((float)t2 - (float)t1) / 1000000.0F ) * 1000); pthread_exit(0); return 0; }
1
#include <pthread.h> static pthread_mutex_t g_tmp_mutex = PTHREAD_MUTEX_INITIALIZER; int run_command(const char *cmd) { int status; char *tmp = (char *) calloc(strlen(cmd)+50, sizeof(char)); sprintf(tmp, "%s > /dev/null 2>&1", cmd); if(-1 == (status=system(tmp))) { printf("Error: Failed to run command %s (%s) \\n", tmp, strerror(errno)); free(tmp); return -1; } if(WIFEXITED(status)) { if(WEXITSTATUS(status)) { printf("Error: Failed to run cmd [%s]\\n", cmd); free(tmp); return -1; } } free(tmp); return 1; } int create_temp_file(char *tmp_name) { pthread_mutex_lock(&g_tmp_mutex); sprintf(tmp_name, "%s/%s", "/tmp", "delme_tmpfile.XXXXXX"); int fd; if((fd=mkstemp(tmp_name)) && (fd==-1)) { printf("Error: Failed to run mkstemp: %s\\n", strerror(errno)); pthread_mutex_unlock(&g_tmp_mutex); exit(1); } pthread_mutex_unlock(&g_tmp_mutex); return fd; } void remove_temp_file(int fd, char *tmp_name) { pthread_mutex_lock(&g_tmp_mutex); if (close (fd) == -1) { printf("Error: Failed to close fd of tmp file = %s\\n", tmp_name); exit(1); } if(-1 == remove(tmp_name)) { printf("Error: Failed to run remove: %s\\n", strerror(errno)); exit(1); } pthread_mutex_unlock(&g_tmp_mutex); } void twod_free_memory(char **result) { unsigned int i, num_lines = atoi(result[0]); for(i=0; i<num_lines; i++) { free(result[i]); } free(result); } int copy_lines_to_2d_array(char *ptr, size_t size, char ***ret) { off_t i, num_lines = 2; for(i=0; i<size; i++) if(ptr[i] == '\\n') num_lines++; char **result = (char **) calloc(num_lines + 1, sizeof(char *)); result[0] = (char *) calloc(20, sizeof(char)); sprintf(result[0], "%d", 0); off_t ncount= 1; int found = 0; char *lstart=ptr, *lend; for(i=0; i<size; i++) { if((ptr[i] == '\\n')) { found = 1; lend = ptr + i + 1; off_t llength = lend - lstart; if(llength > 0) { result[ncount] = (char *) calloc(llength+1, sizeof(char)); memcpy(result[ncount], lstart, llength); result[ncount][llength] = '\\0'; lstart = lend; ncount++; } else { printf("Error: Some problem no chars nfound\\n"); twod_free_memory(result); return -5; } } } if(!found) { lend = ptr + i; off_t llength = lend - lstart; if(llength > 0) { result[ncount] = (char *) calloc(llength+1, sizeof(char)); memcpy(result[ncount], lstart, llength); result[ncount][llength] = '\\0'; } } sprintf(result[0], "%lu", (long)ncount); *ret = result; return 0; } int read_file(int fd, char ***result) { struct stat sb; int ret = 0; if (-1 == fstat (fd, &sb)) { printf("Error: Failed to fstat file fd=%d\\n", fd); return -1; } if(sb.st_size == 0) { printf("Warning: No data to read from file (Bytes=%ld) ", sb.st_size); return -2; } if (!S_ISREG (sb.st_mode)) { printf("Error: fd=%d is not a file\\n", fd); return -3; } char *ptr = (char *)mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if (ptr == MAP_FAILED) { printf("Error: Failed to mmap file \\n"); return -4; } ret = copy_lines_to_2d_array(ptr, sb.st_size, result); if (-1 == munmap (ptr, sb.st_size)) { printf("Error: Failed to munmap \\n"); return -5; } return ret; } int execute_command(char *cmd, int *status, char ***result) { int ret = 0; if(cmd) { char tmp_name[50]; int fd = create_temp_file(tmp_name); int len = strlen(cmd) + strlen(tmp_name) + 20; char *tmp_cmd = (char *) calloc(len, sizeof(char)); sprintf(tmp_cmd, "%s%s%s%s", cmd, " > ", tmp_name, " 2>&1"); printf("CMD: %s\\n", tmp_cmd); if((*status=system(tmp_cmd)) && (*status==-1)) { printf("Error: Failed to run system: %s\\n", strerror(errno)); close(fd); free(tmp_cmd); return -1; } free(tmp_cmd); ret = read_file(fd, result); remove_temp_file(fd, tmp_name); } else printf("Error: CMD is NULL\\n"); return ret; } int main(int argc, char *argv[]) { char **result; int status = 0; char *cmd = "ls -al"; unsigned int i; int ret = 0; if((ret = execute_command(cmd, &status, &result)) == 0) { printf("Number of result Lines: %ld \\n", atol(result[0]) - 1); for(i=1; i<atol(result[0]); i++) { printf("%s", result[i]); } twod_free_memory(result); } else { printf ("Error: Failed to execute command %d \\n", ret); } }
0
#include <pthread.h> int dato = 5; int n_lect = 0; void *Lector(void *arg); void *Escritor(void *arg); int main(int argc, char *argv[]) { pthread_t th1, th2, th3, th4; pthread_create(&th1, 0, Lector, 0); pthread_create(&th2, 0, Escritor, 0); pthread_create(&th3, 0, Lector, 0); pthread_create(&th4, 0, Escritor, 0); pthread_join(th1, 0); pthread_join(th2, 0); pthread_join(th3, 0); pthread_join(th4, 0); exit(0); } void *Lector(void *arg) { while(1){ pthread_mutex_lock(&lectores); n_lect ++; if(n_lect==1) pthread_mutex_lock(&cerrojo); pthread_mutex_unlock(&lectores); printf("%d\\n", dato); pthread_mutex_lock(&lectores); n_lect--; if(n_lect==0) pthread_mutex_unlock(&cerrojo); pthread_mutex_unlock(&lectores); } } void *Escritor(void *arg){ while(1){ pthread_mutex_lock(&cerrojo); dato = dato + 5; printf("modificando %d\\n", dato); pthread_mutex_unlock(&cerrojo); sleep(5); } }
1
#include <pthread.h> void* produzir(void *p) { while(1){ pthread_mutex_lock(&mutex); while (buffer == tamanho_buffer) { printf("PRODUTOR %d: Buffer CHEIO. Indo dormir\\n",(int)(size_t)p); pthread_cond_wait(&condp, &mutex); } buffer += 1; printf("PRODUTOR %d: Acordado! Produzindo...\\n",(int)(size_t)p); pthread_cond_signal(&condc); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void* consumir(void *p) { while(1) { pthread_mutex_lock(&mutex); while (buffer == 0){ printf("CONSUMIDOR %d: Buffer VAZIO. Indo dormir\\n",(int)(size_t)p); pthread_cond_wait(&condc, &mutex); } buffer -= 1; printf("CONSUMIDOR %d: Acordado! Consumindo...\\n",(int)(size_t)p); pthread_cond_signal(&condp); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char **argv) { tamanho_buffer = atoi(argv[1]); buffer = 0; pthread_t thread_produtor[QTD_T_PRODUTOR], thread_consumidor[QTD_T_CONSUMIDOR]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); int i; for (i = 0; i < QTD_T_PRODUTOR; ++i) pthread_create(&thread_produtor[i], 0, produzir, (void *)(size_t) i); for (i = 0; i < QTD_T_CONSUMIDOR; ++i) pthread_create(&thread_consumidor[i], 0, consumir, (void *)(size_t) i); for (i = 0; i < QTD_T_PRODUTOR; ++i) pthread_join(thread_produtor[i], 0); for (i = 0; i < QTD_T_CONSUMIDOR; ++i) pthread_join(thread_consumidor[i], 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
0
#include <pthread.h> struct buffer { int b[10]; pthread_mutex_t monitor; pthread_cond_t empty; pthread_cond_t full; int in,out; int fullEntries; } buf; void *producer() { int i=1; while (1) { int item; item=rand()%100; pthread_mutex_lock(&buf.monitor); while (buf.fullEntries == 10) pthread_cond_wait(&buf.empty, &buf.monitor); buf.b[buf.in]=item; printf("\\nProduced at \\tb[%d]:%d",buf.in,item); buf.in=(buf.in+1)%10; buf.fullEntries++; pthread_cond_signal(&buf.full); pthread_mutex_unlock(&buf.monitor); sleep(item%4); } } void *consumer() { while (1) { int item; pthread_mutex_lock(&buf.monitor); while (buf.fullEntries == 0) pthread_cond_wait(&buf.full, &buf.monitor); item=buf.b[buf.out]; printf("\\nConsumed from \\tb[%d]:%d",buf.out,item); buf.out=(buf.out+1)%10; buf.fullEntries--; pthread_cond_signal(&buf.empty); pthread_mutex_unlock(&buf.monitor); sleep(rand()%4); } } int main() { pthread_t tidp,tidc; buf.in=0; buf.out=0; buf.fullEntries=0; if(pthread_create(&tidp,0,producer,0)) { fprintf(stderr, "Error creating producer.\\n"); return 1; } if(pthread_create(&tidc,0,consumer,0)) { fprintf(stderr, "Error creating producer.\\n"); return 1; } pthread_join(tidp,0); pthread_join(tidc,0); sleep(5); exit(0); }
1
#include <pthread.h> static pthread_mutex_t gethostby_mutex = PTHREAD_MUTEX_INITIALIZER; static int convert (struct hostent *host, struct hostent *result, char *buf, int buflen, int *h_errnop) { int len, i; if (!buf || !h_errnop) return -1; *h_errnop = h_errno; *result = *host; result->h_name = (char *) buf; len = strlen (host->h_name) + 1; if (len > buflen) return -1; buflen -= len; buf += len; strcpy ((char *) result->h_name, host->h_name); for (len = sizeof (char *), i = 0; host->h_aliases [i]; i++) { len += strlen (host->h_aliases [i]) + 1 + sizeof (char *); } if (len > buflen) return -1; buflen -= len; result->h_aliases = (char **) buf; buf += (i + 1) * sizeof (char *); for (i = 0; host->h_aliases [i]; i++) { result->h_aliases [i] = (char *) buf; strcpy (result->h_aliases [i], host->h_aliases [i]); buf += strlen (host->h_aliases [i]) + 1; } result->h_aliases [i] = 0; len = strlen (host->h_addr) + 1 + sizeof (char *); if (len > buflen) return -1; result->h_addr = (char *) buf; strcpy (result->h_addr, host->h_addr); return 0; } struct hostent * gethostbyaddr_r (const char *addr, int length, int type, struct hostent *result, char *buffer, int buflen, int *h_errnop) { struct hostent *host; pthread_mutex_lock (&gethostby_mutex); host = gethostbyaddr (addr, length, type); if (!host || convert (host, result, buffer, buflen, h_errnop) != 0) { result = 0; } pthread_mutex_unlock (&gethostby_mutex); return result; } struct hostent * gethostbyname_r (const char *name, struct hostent *result, char *buffer, int buflen, int *h_errnop) { struct hostent *host; pthread_mutex_lock (&gethostby_mutex); host = gethostbyname (name); if (!host || convert (host, result, buffer, buflen, h_errnop) != 0) { result = 0; } pthread_mutex_unlock (&gethostby_mutex); return result; } struct hostent * gethostent_r (struct hostent *result, char *buffer, int buflen, int *h_errnop) { struct hostent *host; pthread_mutex_lock (&gethostby_mutex); host = gethostent (); if (!host || convert (host, result, buffer, buflen, h_errnop) != 0) { result = 0; } pthread_mutex_unlock (&gethostby_mutex); return result; }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; struct foo * foo_alloc(int id) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void * thr_fn1(void *arg) { printf("thread 1: ID is %lu\\n", (unsigned long)pthread_self()); struct foo * foo = arg; for(int i=0; i< 3; i++){ usleep(500); foo_hold(foo); printf("thr_fn1, foo->f_count number: %d\\n", foo->f_count); foo_rele(foo); printf("thr_fn1, foo->f_count number: %d\\n", foo->f_count); } pthread_exit((void *)&foo); } void * thr_fn2(void *arg) { printf("thread 2: ID is %lu\\n", (unsigned long)pthread_self()); struct foo * foo = arg; for(int i=0; i< 3; i++){ usleep(300); foo_hold(foo); printf("thr_fn2, foo->f_count number: %d\\n", foo->f_count); foo_rele(foo); printf("thr_fn2, foo->f_count number: %d\\n", foo->f_count); } pthread_exit((void *)0); } int main(void) { int err; pthread_t tid1, tid2; void *tret; struct foo * foo = foo_alloc(1); if (0 == foo) err_exit((int)foo, "foo_alloc err "); err = pthread_create(&tid1, 0, thr_fn1, foo); if (err != 0) err_exit(err, "can't create thread 1"); err = pthread_create(&tid2, 0, thr_fn2, foo); if (err != 0) err_exit(err, "can't create thread 2"); sleep(1); err = pthread_join(tid1, (void *)&tret); if (err != 0) err_exit(err, "can't join with thread 1"); err = pthread_join(tid2, (void *)&tret); if (err != 0) err_exit(err, "can't join with thread 2"); foo_rele(foo); printf("parent, foo->f_count number: %d\\n", foo->f_count); exit(0); }
1
#include <pthread.h> { struct msg *m_next; }msg; msg *workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void process_msg(void) { msg *mp = 0; while(1) { pthread_mutex_lock(&qlock); while(workq == 0) { pthread_cond_wait(&qready, &qlock); } mp = workq; workq = mp->m_next; pthread_mutex_unlock(&qlock); } } void enqueue_msg(msg *mp) { pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); }
0
#include <pthread.h> double distance(double x, double y); void *Op (void *threadD); int *in_circle; pthread_mutex_t *in_circle_lock; int threadID; long long num_tosses; }thread_data; int main (int argc, char *argv[]){ double pi; int i; int points; int numthreads; int in_circle = 0; int iteration; int remain; pthread_t* threads; thread_data* threadD; pthread_mutex_t in_circle_lock; points = atoi(argv[1]); numthreads = atoi(argv[2]); iteration = points / numthreads; remain = points % numthreads; threads = (pthread_t*)malloc(sizeof(pthread_t) * numthreads); threadD = (thread_data*)malloc(sizeof(thread_data) * numthreads); pthread_mutex_init(&in_circle_lock, 0); for(i=0;i<numthreads;i++) { threadD[i].in_circle= &in_circle; threadD[i].in_circle_lock = &in_circle_lock; threadD[i].threadID = i; if(i == 0) threadD[i].num_tosses = iteration + remain; else threadD[i].num_tosses = iteration; pthread_create(&threads[i], 0, Op, (void*)&threadD[i]); } for(i=0; i<numthreads; i++) { pthread_join(threads[i], 0); } pi = 4.0 * ((double)in_circle/(double)(points)); printf("Estimate of Pi is %f\\n",pi); return 0; } void *Op(void *threadD) { int i; double x, y; double dis; int count = 0; thread_data* tData = (thread_data*)threadD; srandom(time(0)); for(i = 0; i < tData->num_tosses; i++) { x = (double)rand()/32767; y = (double)rand()/32767; dis = distance(x,y); if(dis < 1.0) count++; } pthread_mutex_lock(tData->in_circle_lock); *(tData->in_circle) += count; pthread_mutex_unlock(tData->in_circle_lock); pthread_exit(0); } double distance(double x, double y){ double result; result = sqrt((x*x) + (y*y)); return result; }
1
#include <pthread.h> pthread_mutex_t mymutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t mycond = PTHREAD_COND_INITIALIZER; void *mythread1(void *param) { printf("begin mythread1.\\n"); pthread_mutex_lock(&mymutex1); printf("wait in mythread1.\\n"); pthread_cond_wait(&mycond,&mymutex1); pthread_mutex_unlock(&mymutex1); printf("end mythread1.\\n"); return 0; } void *mythread2(void *param) { printf("begin mythread2.\\n"); pthread_mutex_lock(&mymutex1); printf("wait in mythread2.\\n"); pthread_cond_wait(&mycond,&mymutex1); pthread_mutex_unlock(&mymutex1); printf("end mythread2.\\n"); return 0; } int main(void) { printf("begin main thread.\\n"); int i; pthread_t tid1,tid2; pthread_create(&tid1,0,mythread1,0); pthread_create(&tid2,0,mythread2,0); sleep(2); printf("try to wake up mythread1 and mythread2 in main thread.\\n"); if(pthread_cond_broadcast(&mycond)){ printf("error\\n"); return 1; } void *res; pthread_join(tid1, &res); pthread_join(tid2, &res); printf("end main thread.\\n"); return 0; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> struct autosync_cfg { struct jfs *fs; pthread_t tid; time_t max_sec; size_t max_bytes; sig_atomic_t must_die; pthread_cond_t cond; pthread_mutex_t mutex; }; static void *autosync_thread(void *arg) { int rv; void *had_errors; struct timespec ts; struct autosync_cfg *cfg; cfg = (struct autosync_cfg *) arg; had_errors = (void *) 0; pthread_mutex_lock(&cfg->mutex); for (;;) { clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += cfg->max_sec; rv = pthread_cond_timedwait(&cfg->cond, &cfg->mutex, &ts); if (rv != 0 && rv != ETIMEDOUT) break; if (cfg->must_die) break; if (rv != ETIMEDOUT && cfg->fs->ltrans_len < cfg->max_bytes) continue; rv = jsync(cfg->fs); if (rv != 0) had_errors = (void *) 1; } pthread_mutex_unlock(&cfg->mutex); pthread_exit(had_errors); return 0; } int jfs_autosync_start(struct jfs *fs, time_t max_sec, size_t max_bytes) { struct autosync_cfg *cfg; if (fs->as_cfg != 0) return -1; cfg = malloc(sizeof(struct autosync_cfg)); if (cfg == 0) return -1; cfg->fs = fs; cfg->max_sec = max_sec; cfg->max_bytes = max_bytes; cfg->must_die = 0; pthread_cond_init(&cfg->cond, 0); pthread_mutex_init(&cfg->mutex, 0); fs->as_cfg = cfg; return pthread_create(&cfg->tid, 0, &autosync_thread, cfg); } int jfs_autosync_stop(struct jfs *fs) { int rv = 0; void *had_errors; if (fs->as_cfg == 0) return 0; fs->as_cfg->must_die = 1; pthread_cond_signal(&fs->as_cfg->cond); pthread_join(fs->as_cfg->tid, &had_errors); if (had_errors) rv = -1; pthread_cond_destroy(&fs->as_cfg->cond); pthread_mutex_destroy(&fs->as_cfg->mutex); free(fs->as_cfg); fs->as_cfg = 0; return rv; } void autosync_check(struct jfs *fs) { if (fs->as_cfg == 0) return; if (fs->ltrans_len > fs->as_cfg->max_bytes) pthread_cond_signal(&fs->as_cfg->cond); }
0
#include <pthread.h> int NUMBER_OF_WORKER_THREADS = 10; pthread_mutex_t StartWorkMutex; pthread_cond_t StartWorkCondition; Bool WorkOn = FALSE; unsigned int Round = 0; pthread_mutex_t CompleteMutex; pthread_cond_t CompleteCondition; Bool MainThreadWaiting = FALSE; unsigned int TheCompletedBatch = 99; long id; long range_a; long range_b; long res; }student; student *s; void *WorkerThread(void *ThreadArgument){ unsigned int X; long unsigned int ThisThreadNumber = (long unsigned int)ThreadArgument; int rc; int i; pthread_key_t a_key; pthread_mutex_lock(&StartWorkMutex); pthread_cond_wait(&StartWorkCondition, &StartWorkMutex); while ( TRUE ) { sched_yield(); if ( WorkOn ) { printf("Thread-%lu: Begin Work On Batch %d\\n", ThisThreadNumber, Round); s = (student*)malloc(sizeof(student)); rc = pthread_setspecific(a_key,s); for(X=0;X<1;++X){ s->id = rand()%10+1; s->range_a = rand()%10+1; s->range_b = rand()%10 + s->range_a; s->res = 0; if(s->id % 3 == 0){ s->res = 0; for(i=s->range_a; i < s->range_b; ++i) s->res = s->res+i; } if(s->id % 3 == 1){ s->res = 1; for(i=s->range_a; i < s->range_b; ++i) s->res = s->res*i*i; } if(s->id % 3 == 2){ s->res = 1; for(i=s->range_a; i<s->range_b; ++i) s->res = s->res*i; } printf("thread:%lu student id: %ld, mod: %ld, range: a = %ld, b = %ld, res = %ld\\n",ThisThreadNumber,s->id, s->id%3, s->range_a, s->range_b, s->res); free(s); } pthread_mutex_unlock(&StartWorkMutex); } else { pthread_mutex_unlock(&StartWorkMutex); pthread_exit(0); } while ( TRUE ) { pthread_mutex_lock(&CompleteMutex); if ( MainThreadWaiting == TRUE ) { MainThreadWaiting = FALSE; break; } pthread_mutex_unlock(&CompleteMutex); } TheCompletedBatch = ThisThreadNumber; pthread_mutex_lock(&StartWorkMutex); pthread_cond_signal(&CompleteCondition); pthread_mutex_unlock(&CompleteMutex); pthread_cond_wait(&StartWorkCondition, &StartWorkMutex); } } int main(int argc, char *argv[]){ long unsigned int Identity; unsigned int X; unsigned int Y; pthread_t Threads[NUMBER_OF_WORKER_THREADS]; pthread_attr_t attr; NUMBER_OF_WORKER_THREADS = atoi(argv[1]); printf("Number of worker threads:%d\\n", NUMBER_OF_WORKER_THREADS); pthread_mutex_init(&CompleteMutex, 0); pthread_cond_init (&CompleteCondition, 0); pthread_mutex_init(&StartWorkMutex, 0); pthread_cond_init (&StartWorkCondition, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for ( Identity = 0; Identity < NUMBER_OF_WORKER_THREADS; Identity++ ) pthread_create(&Threads[Identity], &attr, WorkerThread, (void *)Identity); printf("Wait for 1 second for the %d worker threads to enter a waiting state.\\n\\n", NUMBER_OF_WORKER_THREADS); pthread_mutex_lock(&StartWorkMutex); WorkOn = TRUE; printf("Main: Broadcast Signal To Start Batch| |\\n"); pthread_mutex_lock(&CompleteMutex); pthread_cond_broadcast(&StartWorkCondition); pthread_mutex_unlock(&StartWorkMutex); for ( Y = 0; Y < NUMBER_OF_WORKER_THREADS; Y++ ) { MainThreadWaiting = TRUE; pthread_cond_wait(&CompleteCondition, &CompleteMutex); } pthread_mutex_unlock(&CompleteMutex); pthread_mutex_lock(&StartWorkMutex); WorkOn = FALSE; pthread_cond_broadcast(&StartWorkCondition); pthread_mutex_unlock(&StartWorkMutex); for ( X = 0; X < NUMBER_OF_WORKER_THREADS; X++ ) { pthread_join(Threads[X], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&CompleteMutex); pthread_cond_destroy(&CompleteCondition); pthread_mutex_destroy(&StartWorkMutex); pthread_cond_destroy(&StartWorkCondition); pthread_exit (0); }
1
#include <pthread.h> unsigned char uart = 0; pthread_mutex_t rt_mutex; void* pthreat_recv_data(void* para) { int i = 0; int res = 0; unsigned long recv_count = 0; char recv_buf[254] = {0}; if ((uart == 1) || (uart == 2) || (uart == 3)) { while (1) { pthread_mutex_lock(&rt_mutex); if ((res = spi_rt_interface.recv_data(uart, recv_buf, sizeof(recv_buf))) <= 0) { printf("recv error! res = %d\\n", res); } else { printf("recv_data res = %d\\n", res); } recv_count++; printf("recv_count = %d\\n", recv_count); pthread_mutex_unlock(&rt_mutex); usleep(10000); } } else { PRINT("[uart_num error!]\\n"); return (void *)-1; } return (void *)0; } void* pthreat_send_data(void* para) { int i = 0; int res = 0; unsigned long send_count = 0; unsigned char hook_flag = 0; char on_hook[5] = {0xA5, 0x5A, 0x5E, 0x00, 0x5E}; char of_hook[6] = {0xA5, 0x5A, 0x73, 0x01, 0x01, 0x73}; if ((uart == 1) || (uart == 2) || (uart == 3)) { while (1) { pthread_mutex_lock(&rt_mutex); if (hook_flag == 0) { if ((res = spi_rt_interface.send_data(uart, of_hook, sizeof(of_hook))) <= 0) { printf("send of_hook error! res = %d\\n", res); } else { printf("send of_hook success! res = %d\\n", res); } hook_flag = 1; } else { if ((res = spi_rt_interface.send_data(uart, on_hook, sizeof(on_hook))) <= 0) { printf("send on_hook error! res = %d\\n", res); } else { printf("send on_hook success! res = %d\\n", res); } hook_flag = 0; } send_count++; printf("send_count = %d\\n", send_count); pthread_mutex_unlock(&rt_mutex); sleep(1); } } else { PRINT("[uart_num error!]\\n"); return (void *)-1; } return (void *)0; } int main(int argc, char ** argv) { strcpy(common_tools.argv0, argv[0]); signal(SIGSEGV, SIG_IGN); fflush(stdout); if (argc != 2) { PRINT("[cmd uart_num!]\\n"); return -1; } uart = atoi(argv[1]); pthread_t pthread_send_id, pthread_recv_id; pthread_create(&pthread_send_id, 0, (void*)pthreat_send_data, 0); pthread_create(&pthread_recv_id, 0, (void*)pthreat_recv_data, 0); pthread_join(pthread_send_id, 0); pthread_join(pthread_recv_id, 0); return 0; }
0
#include <pthread.h> static pthread_cond_t cond_not_empty = PTHREAD_COND_INITIALIZER; static pthread_cond_t cond_not_full = PTHREAD_COND_INITIALIZER; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int j_produced = 0, j_consumed = 0, nbuf = 24, nmax = 200; volatile int j_active = 0; struct event { int location; }; struct event **buf_struct; void produce (int j) { int location = (j - 1) % nbuf; buf_struct[location]->location = location; printf (" PRODUCE: loc = %3d, id=%3d\\n", location, (int)pthread_self () % 1000); } void consume (int j) { int location = (j - 1) % nbuf; buf_struct[location]->location = location; printf (" CONSUME: loc = %3d, id=%3d\\n", location, (int)pthread_self () % 1000); } void *producer (void *arg) { printf ("Starting the producer thread, id=%3d\\n", (int)pthread_self () % 1000); while (j_produced < nmax) { pthread_mutex_lock (&lock); while (j_active >= nbuf) { { if ( j_produced == nmax){ pthread_mutex_unlock(&lock); { printf ("Exiting the producer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; }}; pthread_cond_wait (&cond_not_full, &lock); } { if ( j_produced == nmax){ pthread_mutex_unlock(&lock); { printf ("Exiting the producer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; }}; j_produced++; j_active++; printf ("prod %3d, active %3d, id=%3d", j_produced, j_active, (int)pthread_self () % 1000); produce (j_produced); pthread_cond_broadcast (&cond_not_empty); pthread_mutex_unlock (&lock); } { printf ("Exiting the producer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; } void *consumer (void *arg) { printf ("Starting the consumer thread, id=%3d\\n", (int)pthread_self () % 1000); while (j_consumed < nmax) { pthread_mutex_lock (&lock); while (j_active == 0) { { if ( j_consumed == nmax ) { pthread_mutex_unlock (&lock); { printf ("Exiting the consumer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; } }; pthread_cond_wait (&cond_not_empty, &lock); } { if ( j_consumed == nmax ) { pthread_mutex_unlock (&lock); { printf ("Exiting the consumer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; } }; j_consumed++; printf ("cons %3d, active %3d, id=%3d", j_consumed, j_active, (int)pthread_self () % 1000); consume (j_consumed); j_active--; pthread_cond_broadcast (&cond_not_full); pthread_mutex_unlock (&lock); } { printf ("Exiting the consumer thread, id=%3d\\n", (int)pthread_self()%1000); pthread_exit (0); }; } int main (int argc, char *argv[]) { pthread_t t_p[4], t_c[7]; void *rc; int j; if (argc > 2) { nmax = atoi (argv[1]); nbuf = atoi (argv[2]); } buf_struct = malloc (nbuf * sizeof (unsigned long)); for (j = 0; j < nbuf; j++) buf_struct[j] = malloc (sizeof (struct event)); for (j = 0; j < 4; j++) pthread_create (&t_p[j], 0, producer, 0); for (j = 0; j < 7; j++) pthread_create (&t_c[j], 0, consumer, 0); for (j = 0; j < 4; j++) pthread_join (t_p[j], &rc); for (j = 0; j < 7; j++) pthread_join (t_c[j], &rc); exit (0); }
1
#include <pthread.h> pthread_mutex_t buffer_mutex, bounded_queue_mutex; int buffer_consumed = 0; int fill = 0, pages_downloaded = 0; char buffer[100][50]; char *fetch(char *link) { pthread_mutex_lock(&bounded_queue_mutex); if(pages_downloaded == 1) { pthread_mutex_unlock(&bounded_queue_mutex); sleep(5); } else pthread_mutex_unlock(&bounded_queue_mutex); 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; } pthread_mutex_lock(&bounded_queue_mutex); pages_downloaded++; pthread_mutex_unlock(&bounded_queue_mutex); 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); pthread_mutex_lock(&bounded_queue_mutex); if(pages_downloaded == 1 && fill > 4) buffer_consumed = 1; pthread_mutex_unlock(&bounded_queue_mutex); } int main(int argc, char *argv[]) { pthread_mutex_init(&buffer_mutex, 0); pthread_mutex_init(&bounded_queue_mutex, 0); int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/small_buffer/pagea", 5, 1, 1, fetch, edge); assert(rc == 0); check(buffer_consumed == 1, "All the links should have been parsed as multiple downloader threads should have consumed the buffer\\n"); return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/small_buffer.out"); }
0
#include <pthread.h> int *partial_list_ptr; int partial_list_size; int a[32*32]; pthread_mutex_t min_val_lock; int min_val = 32767; int num_threads; void * find_min (void *list_ptr) { int start, end, my_min, i, j; my_min = 32767; partial_list_ptr = (int *) list_ptr; start = (*partial_list_ptr * partial_list_size); end = start + partial_list_size - 1; printf ("\\nthread%d doing iterations %d to %d \\n", *partial_list_ptr, start, end); for (i = start; i < end; i++) if (a[i] < my_min) my_min = a[i]; printf ("(Thread%d says....) my_min is %d\\n", *partial_list_ptr, my_min); pthread_mutex_lock (&min_val_lock); if (my_min < min_val) min_val = my_min; printf ("Thread%d says:global minimum after updation is..%d\\n", *partial_list_ptr, min_val); pthread_mutex_unlock (&min_val_lock); pthread_exit (0); } int main (int argc, char *argv[]) { pthread_t *threads; int i, start, ret_count; int *tids; struct timeval tv_start, tv_end; struct timezone tz_start, tz_end; double time; if (argc != 2) printf ("Syntax:./a.out <num of threads>\\n"); num_threads = atoi (argv[1]); if (num_threads > 8) { printf ("num threads shouldn't exceed 8\\n"); printf ("Sorry..... Aborting.........\\n"); return; } printf ("\\n\\nFinding the minimum value in a list.......\\n\\n"); for (i = 0; i < 32*32; i++) { a[i] = i + 10; } partial_list_size = 32*32 / num_threads; threads = (pthread_t *) malloc (sizeof (pthread_t) * num_threads); tids = (int *) malloc (sizeof (int) * num_threads); if (ret_count = pthread_mutex_init (&min_val_lock, 0)) { printf ("Error:return code from pthread_mutex_init() is\\n %d", ret_count); exit (-1); } gettimeofday (&tv_start, &tz_start); for (i = 0; i < num_threads; i++) { tids[i] = i; if (ret_count = pthread_create (&threads[i], 0, find_min, &tids[i])) { printf ("Error:return code form pthread_create() is %d\\n", ret_count); exit (-1); } } for (i = 0; i < num_threads; i++) { if (ret_count = pthread_join (threads[i], 0)) { printf ("Error:pthread_join error,return code is %d\\n", ret_count); exit (-1); } } if (ret_count = pthread_mutex_destroy (&min_val_lock)) { printf ("Error:return code is %d \\n", ret_count); exit (-1); } printf ("\\nMinimum value in the list is %d\\n \\n", min_val); gettimeofday (&tv_end, &tz_end); time = tv_end.tv_sec * 1000000 + tv_end.tv_usec - (tv_start.tv_sec * 1000000 + tv_start.tv_usec); time /= 1000000; printf ("Total time required to complete the task is %g seconds\\n", time); }
1
#include <pthread.h> static FILE* __fp = 0; static int __tracer_start = 0; static uintptr_t __func_entry = 0; static pthread_mutex_t _fmutex = PTHREAD_MUTEX_INITIALIZER; void __cyg_profile_func_enter(void* this, void* callsite) ; void __cyg_profile_func_exit(void* this, void* callsite) ; static void _dump_profile_enter_info(void* function, void* caller) { if (!__fp) { return; } pthread_t current = pthread_self(); pthread_mutex_lock(&_fmutex); int n = fprintf(__fp, "%lu|E|%p|%p\\n", current, function, caller); if (n < 0) { printf("dump entrance trace info failed: %s\\n", strerror(errno)); } pthread_mutex_unlock(&_fmutex); } void _dump_profile_exit_info(void* function, void* caller) { if (!__fp) { return; } pthread_t current = pthread_self(); pthread_mutex_lock(&_fmutex); int n = fprintf(__fp, "%lu|X|%p|%p\\n", current, function, caller); if (n < 0) { printf("dump exit trace info failed: %s\\n", strerror(errno)); } pthread_mutex_unlock(&_fmutex); } void __cyg_profile_func_enter(void* function, void* caller) { if (!__tracer_start) { if (__func_entry && __func_entry == (uintptr_t)function) { __tracer_start = 1; printf("enter in function(%p), tracer start\\n", function); } else { return; } } _dump_profile_enter_info(function, caller); } void __cyg_profile_func_exit(void* function, void* caller) { if (!__tracer_start) { return; } _dump_profile_exit_info(function, caller); } void main_constructor(void) ; void main_destructor(void) ; static void tracer_sighandler(int sig) { __tracer_start = 1; } void main_constructor(void) { char* trace_file = getenv("FTRACER_FILE"); if (!trace_file) { trace_file = "/tmp/trace.txt"; } __fp = fopen(trace_file, "w"); if (__fp == 0) { printf("can not open trace.txt\\n"); return; } printf("open trace file: %s success\\n", trace_file); char* func_entry = getenv("FTRACER_FUNC_ENTRY"); if (func_entry) { __func_entry = strtoul(func_entry, 0, 16); if (!__func_entry) { printf("Warning: %s is invalid, tracer is disabled: %s\\n", "FTRACER_FUNC_ENTRY", strerror(errno)); } else { printf("tracer will start when function(%p) is called\\n", (void*)__func_entry); } return; } char* sig_num_str = getenv("FTRACER_SIG_NUM"); if (sig_num_str) { int sig_num = (int)strtoul(sig_num_str, 0, 10); if (sig_num <= 0 ) { printf("Warning: %s is invalid, tracer is disabled: sig_num = %d\\n", "FTRACER_SIG_NUM", sig_num); return; } struct sigaction sa; sa.sa_handler = tracer_sighandler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(sig_num, &sa, 0); printf("tracer will start when receive signal number = %d\\n", sig_num); return; } __tracer_start = 1; printf("tracer start\\n"); } void main_deconstructor(void) { if (__fp) { fclose(__fp); printf("close trace file\\n"); } }
0
#include <pthread.h> int curr[5][3]; int max_need[5][3]; int finish[5]; int max_res[3]; int avail[3]; pthread_mutex_t mutex; void* Banker(void*); void Print_state(); int main(){ pthread_t tid[5]; pthread_attr_t attr; int i, j; for (i=0;i<5;i++){ finish[i] = 0; for (j=0;j<3;j++){ curr[i][j] = 0; max_need[i][j] = 0; } } printf("Give the max number of each resources:\\n"); for (i=0;i<3;i++){ scanf("%d", &max_res[i]); } printf("\\nGive the number of available resources:\\n"); for (i=0;i<3;i++){ scanf("%d", &avail[i]); } printf("\\nGive the current allocation of each process:\\n"); for (i=0;i<5;i++){ printf("p%d ", i+1); for (j=0;j<3;j++){ scanf("%d", &curr[i][j]); } } for (j=0;j<3;j++){ int tmp=0; for (i=0;i<5;i++){ tmp += curr[i][j]; } if (avail[j]+tmp != max_res[j]){ fprintf(stderr, "Wrong setting\\n"); return 0; } } printf("\\nGive the max number of resources each process may need:\\n"); for (i=0;i<5;i++){ printf("p%d ", i+1); for (j=0;j<3;j++){ scanf("%d", &max_need[i][j]); } } for (i=0;i<5;i++){ for (j=0;j<3;j++){ if (max_need[i][j] > max_res[j]){ fprintf(stderr, "Wrong setting\\n"); return 0; } } } Print_state(); printf("\\nStart the Banker's algorithm\\n"); pthread_attr_init(&attr); pthread_mutex_init(&mutex, 0); for (i=0;i<5;i++) pthread_create(&tid[i], &attr, Banker, (void*)i); for (i=0;i<5;i++) pthread_join(tid[i], 0); printf("\\nAll processes have finished\\n"); pthread_exit(0); return 0; } void* Banker(void* Pid){ int pid = (int*)Pid; int j; bool wait = 1; while (finish[pid] == 0){ while (wait){ wait = 0; for (j=0;j<3;j++){ int need = max_need[pid][j] - curr[pid][j]; if (need > avail[j]){ wait = 1; } } } pthread_mutex_lock(&mutex); printf("\\nProcess p%d is allocated with: ", pid+1); for (j=0;j<3;j++){ int need = max_need[pid][j] - curr[pid][j]; printf("%d ", need); curr[pid][j] += need; avail[j] -= need; } finish[pid] = 1; for (j=0;j<3;j++){ if (max_need[pid][j] != curr[pid][j]) finish[pid] = 0; } if (finish[pid] == 1){ printf("\\np%d has finished\\n", pid+1); for (j=0;j<3;j++){ avail[j] += curr[pid][j]; curr[pid][j] = 0; max_need[pid][j] = 0; } } Print_state(); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void Print_state(){ int i, j; printf("\\n---------------------------------"); printf("\\nCurrent available resources: "); for (i=0;i<3;i++) printf("%d ", avail[i]); printf("\\n"); printf("\\nCurrent max_need table:\\n"); for (i=0;i<5;i++){ printf("p%d", i+1); for (j=0;j<3;j++){ printf("%3d", max_need[i][j]); } printf("\\n"); } printf("\\nCurrent allocation table:\\n"); for (i=0;i<5;i++){ printf("p%d", i+1); for (j=0;j<3;j++){ printf("%3d", curr[i][j]); } printf("\\n"); } printf("\\nCurrent need table:\\n"); for (i=0;i<5;i++){ printf("p%d", i+1); for (j=0;j<3;j++){ printf("%3d", max_need[i][j] - curr[i][j]); } printf("\\n"); } }
1
#include <pthread.h> char sourceFilename[ 500 ], destinationFilename[ 500 ], nonFlatSourceFilename[ 500 ], nonFlatDestinationFilename[ 500 ]; off_t offset = 0; pthread_mutex_t offsetMutex = PTHREAD_MUTEX_INITIALIZER; int copyingDone = 0; void *copyWorker() { char buf[ 4096 ]; time_t startedAt = time( 0 ); int sourceFd = open( sourceFilename, O_RDONLY ); int destinationFd = open( destinationFilename, O_WRONLY | O_CREAT, 0666 ); int res; do { pthread_mutex_lock( &offsetMutex ); res = pread( sourceFd, &buf, 4096, offset ); if ( res == 0 ) break; pwrite( destinationFd, buf, res, offset ); offset += 4096; pthread_mutex_unlock( &offsetMutex ); } while ( res == 4096 ); close( sourceFd ); close( destinationFd ); time_t endedAt = time( 0 ); printf( "Copying Done! in %ld seconds\\n", ( endedAt - startedAt ) ); copyingDone = 1; } void copyNonFlatFile() { char buf[ 4096 ]; off_t nonFlatOffset = 0; time_t startedAt = time( 0 ); int nonFlatSourceFd = open( nonFlatSourceFilename, O_RDONLY ); int nonFlatDestinationFd = open( nonFlatDestinationFilename, O_WRONLY | O_CREAT, 0666 ); int res; do { res = pread( nonFlatSourceFd, &buf, 4096, nonFlatOffset ); if ( res == 0 ) break; pwrite( nonFlatDestinationFd, buf, res, nonFlatOffset ); nonFlatOffset += 4096; } while ( res == 4096 ); close( nonFlatSourceFd ); close( nonFlatDestinationFd ); time_t endedAt = time( 0 ); printf( "Non-Flat Copying Done! in %ld seconds\\n", ( endedAt - startedAt ) ); } void runDestinationVM() { char storageCommandBuffer[ 500 ], destinationChangeUUIDCommand[ 500 ]; time_t startedAt = time( 0 ); sprintf( destinationChangeUUIDCommand, "VBoxManage internalcommands sethduuid \\"%s\\"", nonFlatDestinationFilename ); sprintf( storageCommandBuffer, "VBoxManage storageattach Destination --medium \\"%s\\" --storagectl \\"IDE\\" --port 0 --device 0 --type hdd", nonFlatDestinationFilename ); system( destinationChangeUUIDCommand ); time_t endedAt = time( 0 ); printf( "Running Destination in %ld seconds\\n", ( endedAt - startedAt ) ); } void *sendOffset( void *recvConnection ) { int connection = ( intptr_t ) recvConnection; char offsetBuffer[ 50 ]; char clientMessage[ 2000 ]; do { memset( offsetBuffer, 0, 50 ); memset( clientMessage, 0, 2000 ); recv( connection , clientMessage , 2000 , 0 ); if ( copyingDone == 0 ) { pthread_mutex_lock( &offsetMutex ); printf( "\\tCopying Suspended for a while\\n" ); sprintf( offsetBuffer, "%zu", offset ); printf( "\\t\\tTo Be Sent Offset = %s\\n", offsetBuffer ); printf( "\\t\\tTHE Offset = %zu\\n", offset ); sendMessage( connection, offsetBuffer ); printf( "\\tWaiting the Client to Resume Copying\\n" ); recv( connection , clientMessage , 2000 , 0 ); printf( "\\tCopying Process has been resumed\\n" ); printf( "\\t==========\\n" ); pthread_mutex_unlock( &offsetMutex ); } else { if ( strcmp( clientMessage, "SUSPENDING" ) != 0 ) { printf( "\\tSending to the filesystem that the process done!\\n" ); strcpy( offsetBuffer, "DONE" ); sendMessage( connection, offsetBuffer ); } else if ( strcmp( clientMessage, "SUSPENDED" ) == 0 ) { printf( "\\n\\nSource Suspended\\n\\n\\n" ); } } } while ( strcmp( clientMessage, "CLOSE" ) != 0 ); close( connection ); printf( "\\tConnection Closed\\n" ); copyNonFlatFile(); runDestinationVM(); } void connectionHandler( int connection ) { pthread_t thread; pthread_create( &thread, 0, sendOffset, ( void * ) ( intptr_t ) connection ); } void *runServer() { createServer( connectionHandler ); } void getVMsInfo( int debugMode ) { if ( debugMode == 1 ) { strcpy( sourceFilename, "/media/maastaar/b9d26bcf-e76e-43da-aa79-c53367b81fa2/maastaar/VirtualBox VMs/Mint Source/Mint Source-flat.vmdk" ); strcpy( nonFlatSourceFilename, "/media/maastaar/b9d26bcf-e76e-43da-aa79-c53367b81fa2/maastaar/VirtualBox VMs/Mint Source/Mint Source.vmdk" ); strcpy( destinationFilename, "/media/maastaar/b9d26bcf-e76e-43da-aa79-c53367b81fa2/maastaar/VirtualBox VMs/Mint Destination/Mint Source-flat.vmdk" ); strcpy( nonFlatDestinationFilename, "/media/maastaar/b9d26bcf-e76e-43da-aa79-c53367b81fa2/maastaar/VirtualBox VMs/Mint Destination/Mint Source.vmdk" ); } else { printf( "Source File Path: " ); fgets( sourceFilename, sizeof( sourceFilename ), stdin ); printf( "Source File Path (non-flat): " ); fgets( nonFlatSourceFilename, sizeof( nonFlatSourceFilename ), stdin ); printf( "Destination File Path (Will be created automatically): " ); fgets( destinationFilename, sizeof( destinationFilename ), stdin ); printf( "Destination File Path (non-flat) (Will be created automatically): " ); fgets( nonFlatDestinationFilename, sizeof( nonFlatDestinationFilename ), stdin ); sourceFilename[ strlen( sourceFilename ) - 1 ] = '\\0'; nonFlatSourceFilename[ strlen( nonFlatSourceFilename ) - 1 ] = '\\0'; destinationFilename[ strlen( destinationFilename ) - 1 ] = '\\0'; nonFlatDestinationFilename[ strlen( nonFlatDestinationFilename ) - 1 ] = '\\0'; } } main() { pthread_t copyWorkerThread, serverThread; getVMsInfo( 1 ); pthread_create( &copyWorkerThread, 0, copyWorker, 0 ); pthread_create( &serverThread, 0, runServer, 0 ); pthread_join( copyWorkerThread, 0 ); pthread_join( serverThread, 0 ); printf( "Done!" ); }
0
#include <pthread.h> const int debug_variable = 0; void callback(int op, int arg1, int arg2) { if (op == 1) printf("Setting/getting address %d, to %d\\n", op, arg1); } const int PAGE_SIZE = 4, MEM_SIZE = 5, ADDR_SPACE_SIZE = 10, MAX_CONCURRENT_OPERATIONS = 4, WRITING_CYCLES = 10, CHECKING_CYCLES = 100, THREADS_PER_BYTE = 6; static pthread_mutex_t test_mutex = PTHREAD_MUTEX_INITIALIZER; void* checking_thread(void *data) { unsigned addr = (unsigned)data; int i; if (debug_variable) printf("Checking address: %u\\n", addr); if (!debug_variable) { for (i = 0; i < CHECKING_CYCLES; ++i) { uint8_t v; if (page_sim_get(addr, &v) != 0) { printf("BUG :(\\n"); exit(2); } pthread_mutex_lock(&test_mutex); printf("Checking address %u, got: %u\\n", addr, (unsigned)v); pthread_mutex_unlock(&test_mutex); if (v != 2 * addr + 1 && v != 2*addr + 2 && v != 0) { printf("BUG :(\\n"); exit(3); } } } } void* writing_thread(void *data) { uint8_t v = (unsigned)data; unsigned addr = v/2; unsigned uv = v; int i; if (debug_variable) printf("Writing to address: %u, value: %u\\n", addr, uv); if (!debug_variable) { for (i = 0; i < WRITING_CYCLES; ++i) { pthread_mutex_lock(&test_mutex); printf("Writing to address %u, value: %u\\n", addr, uv); pthread_mutex_unlock(&test_mutex); if (page_sim_set(addr, v + 1) != 0) { printf("BUG :(\\n"); exit(1); } } } } int main() { assert(page_sim_init(PAGE_SIZE, MEM_SIZE, ADDR_SPACE_SIZE, MAX_CONCURRENT_OPERATIONS, callback) == 0); int i, j, k; for (i = 0; i < MEM_SIZE * PAGE_SIZE; ++i) assert(page_sim_set(i, 0) == 0); int threads_number = PAGE_SIZE * MEM_SIZE * (THREADS_PER_BYTE + 1); pthread_t * threads = malloc(threads_number * sizeof(pthread_t)); int num = 0, write_num=0; for(i = 0; i < MEM_SIZE; ++i) for (j = 0; j < PAGE_SIZE; ++j) { for (k = 0; k < THREADS_PER_BYTE; ++k) { if (pthread_create(threads + num, 0, writing_thread, (void *)(2*write_num + (k&1)))) { printf("%d: \\n", 2*write_num + (k&1)); printf("Pthread error\\n"); return 1; } num++; } if (pthread_create(threads + num , 0, checking_thread, (void *)(write_num))) { printf("Pthread error\\n"); return 1; } num++; write_num++; } for (i = 0; i < threads_number; ++i) pthread_join(threads[i], 0); assert(page_sim_end() == 0); return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); return 0; }
0
#include <pthread.h> int min(int a, int b) { if (a < b) { return a; } else { return b; } } struct data_to_thread { unsigned char * src; unsigned char * dst; int xsize, ysize, start_y, end_y, radius; pthread_barrier_t* barrier; pthread_mutex_t* lock; int* sum; } data_to_thread; static void * blurfiltermpi(void *arguments) { struct data_to_thread* data = (struct data_to_thread *) arguments; unsigned char *src = data->src; unsigned char *dst = data->dst; int xsize = data->xsize; int ysize = data->ysize; int start_y = data->start_y; int end_y = data->end_y; int radius = data->radius; double w[1000]; get_gauss_weights(radius, w); double red, green, blue, n, temp_weight; register unsigned char* temp_pointer; int sum=0; for (int y = start_y; y < end_y; y++) { for (int x = 0; x < xsize; x++) { temp_pointer = src + (xsize * y + x) * 3; sum+=*temp_pointer+ *(temp_pointer + 1)+*(temp_pointer + 2); } } pthread_mutex_lock(data->lock); *(data->sum)+=sum; pthread_mutex_unlock(data->lock); pthread_barrier_wait (data->barrier); sum=*(data->sum)/(xsize*ysize); for (int y = start_y; y < end_y; y++) { for (int x = 0; x < xsize; x++) { temp_pointer = src + (xsize * y + x) * 3; if(*temp_pointer+ *(temp_pointer + 1)+*(temp_pointer + 2)<sum){ temp_pointer = dst + (xsize * y + x) * 3; *temp_pointer=0; *(temp_pointer+1)=0; *(temp_pointer+2)=0; } else{ temp_pointer = dst + (xsize * y + x) * 3; *temp_pointer=255; *(temp_pointer+1)=255; *(temp_pointer+2)=255; } } } return 0; } int main(int argc, char ** argv) { int radius; int xsize, ysize, colmax, number_of_threads; struct timespec start, stop; double accum; char* src = (char*) malloc(sizeof(unsigned char) * (1000*1000) * 3); char* dst = (char*) malloc(sizeof(unsigned char) * (1000*1000) * 3); unsigned* sum=(unsigned*)malloc(sizeof(unsigned)); *sum=0; if (argc != 5) { fprintf(stderr, "Usage: %s radius threads infile outfile\\n", argv[0]); exit(1); } radius = atoi(argv[1]); number_of_threads = atoi(argv[2]); if ((radius > 1000) || (radius < 1)) { fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\\n", radius, 1000); exit(1); } if (read_ppm(argv[3], &xsize, &ysize, &colmax, (char *) src) != 0) { exit(1); } if (colmax > 255) { fprintf(stderr, "Too large maximum color-component value\\n"); exit(1); } pthread_barrier_t* barrier=(pthread_barrier_t*)malloc(sizeof(pthread_barrier_t)); int s = pthread_barrier_init(barrier, 0, number_of_threads); pthread_mutex_t* lock=( pthread_mutex_t*)malloc(sizeof( pthread_mutex_t)); pthread_mutex_init(lock, 0); int number_of_elements, temp_start, temp_end; struct data_to_thread* arguments[100]; pthread_t* threads[100]; struct data_to_thread* temp_arguments; clock_gettime( CLOCK_REALTIME, &start); for (unsigned int i = 1; i < number_of_threads; i++) { temp_start = i * ysize / number_of_threads; if (temp_start < 0) { temp_start = 0; } temp_end = (i + 1) * ysize / number_of_threads; if (temp_end > ysize) { temp_end = ysize; } if (i == number_of_threads - 1) { temp_end = ysize; } temp_arguments = (struct data_to_thread*) malloc( sizeof(struct data_to_thread)); temp_arguments->end_y = temp_end; temp_arguments->radius = radius; temp_arguments->src = src; temp_arguments->start_y = temp_start; temp_arguments->xsize = xsize; temp_arguments->ysize = ysize; temp_arguments->dst = dst; temp_arguments->barrier=barrier; temp_arguments->lock=lock; temp_arguments->sum=sum; arguments[i] = temp_arguments; threads[i] = (pthread_t*) malloc(sizeof(pthread_t)); pthread_create(threads[i], 0, &blurfiltermpi, (void *) arguments[i]); } temp_arguments = (struct data_to_thread*) malloc( sizeof(struct data_to_thread)); temp_end = (1) * ysize / number_of_threads; if (temp_end > ysize) { temp_end = ysize; } if (0 == number_of_threads - 1) { temp_end = ysize; } temp_arguments->end_y = temp_end; temp_arguments->radius = radius; temp_arguments->src = src; temp_arguments->start_y = 0; temp_arguments->xsize = xsize; temp_arguments->ysize = ysize; temp_arguments->dst = dst; temp_arguments->barrier=barrier; temp_arguments->lock=lock; temp_arguments->sum=sum; arguments[0] = temp_arguments; blurfiltermpi((void *) temp_arguments); for (unsigned int i = 1; i < number_of_threads; i++) { pthread_join(*threads[i], 0); } clock_gettime( CLOCK_REALTIME, &stop); write_ppm(argv[4], xsize, ysize, dst); accum = ( (double)stop.tv_sec - (double)start.tv_sec ) + ( (double)stop.tv_nsec - (double)start.tv_nsec ) / 1000000000L;; printf( "it took: %lf\\n", accum ); free(dst); free(src); pthread_mutex_destroy(lock); free(lock); free(barrier); free(sum); for (int i = 0; i < number_of_threads; i++) { free(arguments[i]); if (i > 0) { free(threads[i]); } } return 0; }
1
#include <pthread.h> int udpclient(struct argv_and_list *myinput, int my_socket, struct sockaddr_in myaddr, int serverlen ) { int value_to_exit = 1; char buf[BUFSIZE]; pthread_mutex_lock(&myinput->useQueue); while ( 0 == ListCount( (struct List*) myinput->G_list) ) { pthread_cond_wait(&myinput->emptyCount, &myinput->useQueue); } char* string_to_print = ListTrim((struct List*) myinput->G_list); strcpy(buf,string_to_print ); if (strcmp(string_to_print, "!")==0) { printf("exiting udpclient\\n"); value_to_exit = 0; } free(string_to_print); pthread_mutex_unlock(&myinput->useQueue); pthread_cond_signal(&myinput->fullCount); if ( -1 == sendto(my_socket, buf, strlen(buf), 0, &myaddr, serverlen) ) { printf("ERROR in sendto"); exit(-1); } if ( -1 == recvfrom(my_socket, buf, strlen(buf), 0, &myaddr, &serverlen) ) { printf("ERROR in recvfrom"); exit(-1); } return value_to_exit; }
0
#include <pthread.h> pthread_mutex_t *mutexes; int think(int id, int total, unsigned int *state){ int time = randomGaussian_r(11,7, state); if(time < 0 ) time = 0; printf("Philo %d thinking for %d seconds. (Total = %d)\\n", id, time, total); sleep(time); return time; } int eat(int id, int total, unsigned int *state){ int time = randomGaussian_r(9,3, state); if(time < 0 ) time = 0; printf("Philo %d eating for %d seconds. (Total = %d)\\n", id, time, total); sleep(time); return time; } void dine(int *idPointer){ int id = *idPointer; int eats = 0; int thinks = 0; unsigned int state = id + 1; while(eats < 20){ int thinktemp = think(id, thinks, &state); thinks = thinks + thinktemp; int result = EBUSY; while(result == EBUSY){ pthread_mutex_lock(&mutexes[id]); if((result = pthread_mutex_trylock(&mutexes[(id+1) % 5])) == EBUSY){ pthread_mutex_unlock(&mutexes[id]); } } int eattemp = eat(id, eats, &state); eats = eats + eattemp; pthread_mutex_unlock(&mutexes[id]); pthread_mutex_unlock(&mutexes[(id+1) % 5]); } printf("Philo %d has finished eating, now leaving table\\n", id); } void joinErrMsg(int errnum){ fprintf(stderr, "Error Joining Thread: %d\\n", errnum); exit(1); } void createErrMsg(int errnum){ fprintf(stderr, "Error Creating Thread: %d", errnum); exit(1); } int main(){ pthread_t philo_1, philo_2, philo_3, philo_4, philo_5; int one, two, three, four, five; one = 0; two = 1; three = 2; four = 3; five = 4; mutexes = (pthread_mutex_t *) malloc(5*sizeof(pthread_mutex_t)); for(int i = 0; i < 5; i++){ pthread_mutex_init(&mutexes[i], 0); } int temp; if((temp = pthread_create(&philo_1, 0, (void *) dine, (void *) &one))) createErrMsg(temp); if((temp = pthread_create(&philo_2, 0, (void *) dine, (void *) &two))) createErrMsg(temp); if((temp = pthread_create(&philo_3, 0, (void *) dine, (void *) &three))) createErrMsg(temp); if((temp = pthread_create(&philo_4, 0, (void *) dine, (void *) &four))) createErrMsg(temp); if((temp = pthread_create(&philo_5, 0, (void *) dine, (void *) &five))) createErrMsg(temp); if((temp = pthread_join(philo_1, 0))) joinErrMsg(temp); if((temp = pthread_join(philo_2, 0))) joinErrMsg(temp); if((temp = pthread_join(philo_3, 0))) joinErrMsg(temp); if((temp = pthread_join(philo_4, 0))) joinErrMsg(temp); if((temp = pthread_join(philo_5, 0))) joinErrMsg(temp); return 0; }
1
#include <pthread.h> int num_threads; pthread_t p_threads[65536]; pthread_attr_t attr; pthread_mutex_t lock_barrier; int list[200000000]; int list_size; int prefix_sum_list[200000000]; int mylist_sum[65536]; void *prefix_sum (void *s) { int j, sum, offset; int thread_id = (int) s; int chunk_size = list_size/num_threads; int my_start = thread_id*chunk_size; int my_end = (thread_id+1)*chunk_size-1; if (thread_id == num_threads-1) my_end = list_size-1; sum = list[my_start]; prefix_sum_list[my_start] = sum; for(j = my_start + 1;j <= my_end;j++) { sum += list[j]; prefix_sum_list[j] = sum; } mylist_sum[thread_id] = sum; offset = mylist_sum[0]; for(j = 1;j <= thread_id-1;j++) { offset += mylist_sum[j]; } pthread_mutex_lock(&lock_barrier); if(thread_id != 0) { for(j = my_start; j <= my_end; j++) { prefix_sum_list[j] = prefix_sum_list[j] + offset; } } pthread_mutex_unlock(&lock_barrier); pthread_exit(0); } int main(int argc, char *argv[]) { struct timeval start, stop; double total_time; int i, j; int error; printf("real: %d finished: %d \\n",sizeof(int),0); if (argc != 3) { printf("Need two integers as input \\n"); printf("Use: <executable_name> <list_size> <num_threads>\\n"); exit(0); } if ((list_size = atoi(argv[argc-2])) > 200000000) { printf("Maximum list size allowed: %d.\\n", 200000000); exit(0); }; if ((num_threads = atoi(argv[argc-1])) > 65536) { printf("Maximum number of threads allowed: %d.\\n", 65536); exit(0); }; if (num_threads > list_size) { printf("Number of threads (%d) < list_size (%d) not allowed.\\n", num_threads, list_size); exit(0); }; pthread_mutex_init(&lock_barrier, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); unsigned int seed = 0; srand(seed); for (j = 0; j < list_size; j++) list[j] = rand_r(&seed) % 10; gettimeofday(&start, 0); for (i = 0; i < num_threads; i++) { pthread_create(&p_threads[i], &attr, prefix_sum, (void * )i); } for (i = 0; i < num_threads; i++) { pthread_join(p_threads[i], 0); } gettimeofday(&stop, 0); total_time = (stop.tv_sec-start.tv_sec) +0.000001*(stop.tv_usec-start.tv_usec); error = 0; if (list[0] != prefix_sum_list[0]) error = 1; printf("value: %d ",error); for (j = 1; j < list_size; j++) if (list[j] != (prefix_sum_list[j]-prefix_sum_list[j-1])) error = 1; printf("real: %d finished: %d \\n",sizeof(int), prefix_sum_list[j]-prefix_sum_list[j-1]); if (error) { printf("Houston, we have a problem!\\n"); exit(0); } else { printf("Congratulations. Prefix sum computed correctly\\n"); } printf("Threads = %d, list size = %d, time (sec) = %8.4f\\n", num_threads, list_size, total_time); pthread_attr_destroy(&attr); pthread_mutex_destroy(&lock_barrier); }
0
#include <pthread.h> static struct Queue queue; static pthread_mutex_t mutex; static pthread_mutex_t empty_mutex; static void *QSpoolData(void *args); void QInit(){ pthread_mutex_init(&mutex, 0); pthread_mutex_init(&empty_mutex, 0); pthread_mutex_lock(&empty_mutex); queue.head = 0; queue.tail = 0; return; } int QAddData(uint8_t *data, int size){ struct Element *element; element = (struct Element*) malloc(sizeof(struct Element)); if(element == 0){ return ERR; } pthread_mutex_unlock(&empty_mutex); pthread_mutex_lock(&mutex); element->data = data; element->size = size; element->next = 0; if(queue.tail != 0) queue.tail->next = element; queue.tail = element; if(queue.head == 0) queue.head = queue.tail; pthread_mutex_unlock(&mutex); return 0; } void QStartSpool(int *fd){ pthread_t thread; pthread_create(&thread, 0, QSpoolData, (void*)fd); } static void *QSpoolData(void *args){ struct Element *element; int fd; fd = *((int*)args); if(fd < 0){ pthread_exit(0); } while(1){ pthread_mutex_lock(&empty_mutex); pthread_mutex_lock(&mutex); element = queue.head; if(write(fd, element->data, element->size) < 0){ } queue.head = element->next; if(queue.head == 0){ queue.tail = 0; } else{ pthread_mutex_unlock(&empty_mutex); } pthread_mutex_unlock(&mutex); free(element->data); free(element); } }
1
#include <pthread.h> void print_values(struct filtered_data filteredData){ int i; long sec_elapsed; int ms_elapsed; int us_elapsed; double filtered_channel[4]; double raw_channel[4]; sec_elapsed = filteredData.sec_elapsed; ms_elapsed = filteredData.ms_elapsed; us_elapsed = filteredData.us_elapsed; for(i=0; i < 4; i++) filtered_channel[i] = filteredData.channels[i]; for(i=0; i < 4; i++) raw_channel[i] = filteredData.raw_channels[i]; printf("%ld,%d,%d, raw:%f,%f,%f,%f filtered:%f,%f,%f,%f\\n", sec_elapsed, ms_elapsed, us_elapsed, raw_channel[0], raw_channel[1], raw_channel[2], raw_channel[3], filtered_channel[0], filtered_channel[1], filtered_channel[2], filtered_channel[3]); } void main(int argc, char* argv[]) { int i, j; struct filtered_data filteredData; struct shared* data_ptr = (struct shared*) 0; int shmid; if((shmid = shm_open(SHARED_RESOURCE, O_RDWR , 0600)) == -1) {perror("shm_open"); return;} data_ptr = (struct shared *) mmap(0, sizeof(struct shared), PROT_READ | PROT_WRITE, MAP_SHARED, shmid, 0); if(data_ptr == (struct shared*) (-1)) {perror("mmap"); return;} pthread_mutex_lock(&(data_ptr->mutex)); filteredData.sec_elapsed = data_ptr->filteredData.sec_elapsed; filteredData.ms_elapsed = data_ptr->filteredData.ms_elapsed; filteredData.us_elapsed = data_ptr->filteredData.us_elapsed; for (j = 0; j < 4; j++) { filteredData.channels[j] = data_ptr->filteredData.channels[j]; filteredData.raw_channels[j] = data_ptr->filteredData.raw_channels[j]; } pthread_mutex_unlock(&(data_ptr->mutex)); if(munmap(data_ptr, sizeof(struct shared*)) == -1) {perror("munmap"); return;} print_values(filteredData); }
0
#include <pthread.h> extern int makethread(void *(*)(void *),void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv,0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void *timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait),(0)); (*tip->to_fn)(tip->to_arg); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *),void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0,&now); if((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_sec > now.tv_sec)) { tip = malloc(sizeof(struct to_info)); if(tip != 0) { tip->to_fn = func; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if(when->tv_sec >= now.tv_sec) { tip->to_wait.tv_sec = when->tv_nsec - now.tv_nsec; } else{ tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper,(void *)tip); if(err == 0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err,"pthread_mutexattr_init failed"); if((err = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err,"can't create recursive mutex"); if((err = pthread_mutex_init(&mutex,&attr)) != 0) err_exit(err,"can't create recursive mutex"); pthread_mutex_lock(&mutex); if(condition) { clock_gettime(0,&when); when.tv_sec += 10; timeout(&when,retry,(void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> int g_count = 0; { int numID; }threadID; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void * consume(void *arg) { int inum = 0; inum = (int)arg; while (1) { pthread_mutex_lock(&mutex); while (g_count <= 0) { printf("%d 号消费者开始等待消费 g_count = %d\\n", inum, g_count); pthread_cond_wait(&cond, &mutex); printf("%d 号消费者开始消费 g_count = %d\\n", inum, g_count); } g_count--; printf("%d 号消费者消费完毕...g_count = %d\\n", inum, g_count); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void * produce(void *arg) { int inum = 0; inum = (int)arg; while (1) { pthread_mutex_lock(&mutex); if (g_count > 20) { printf("生产的产品太多需要控制下 休眠....\\n"); sleep(1); continue; } pthread_mutex_unlock(&mutex); sleep(1); pthread_mutex_lock(&mutex); g_count++; printf("%d 号生产者生产完毕... g_count = %d\\n", inum, g_count); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(void) { int ret = 0; int i = 0; pthread_t tidArray[2 + 2]; for (i = 0; i < 2; i++) { ret = pthread_create(&tidArray[i + 2], 0, produce, (void *)i); } for (i = 0; i < 2; i++) { ret = pthread_create(&tidArray[i], 0, consume, (void *)i); } for (i = 0; i < 2 + 2; i++) { pthread_join(tidArray[i], 0); } printf("父进程结束\\n"); return 0; }
0
#include <pthread.h> int fd; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void analyse_psu_info(unsigned int msg_data) { info.data = msg_data; if (PSU != data_id) return; if (PLUG_IN == data_info) { printf("PSU change: psu%d plugged in\\n", data_no); } else if (PLUG_OUT == data_info) { printf("PSU change: psu%d plugged out\\n", data_no); } else if (WORK_FAULT == data_info) { printf("PSU change: psu%d work fault\\n", data_no); } else if (WORK_GOOD == data_info) { printf("PSU change: psu%d work good\\n", data_no); } } void psu_signal_fun(int signum) { unsigned int *info_arr; int i, ret; unsigned long msg_num = 0; printf("signal handle fun, get a signal\\n"); pthread_mutex_lock(&mutex); ret = ioctl(fd, READ_PSU_INFO, &msg_num); if (ret < 0){ printf("ioctrl failed, ret = %d\\n", ret); return; } printf("ret = %d, MSG num : %ld\\n", ret, msg_num); if (ret == 0 && msg_num > 0) { info_arr = malloc(msg_num * sizeof(unsigned int)); if (!info_arr) { printf("No memory\\n"); return; } ret = read(fd, info_arr, sizeof(unsigned int) * msg_num); if (ret < 0) { printf("msg_num is not correct\\n"); return; } else if (ret != msg_num) printf("info msg num left %d\\n", ret); for (i = 0; i < msg_num; ++i) { analyse_psu_info(info_arr[i]); } } free(info_arr); pthread_mutex_unlock(&mutex); } int main(int argc, char **argv) { unsigned char key_val; int ret, Oflags, num; time_t timep; struct sigaction act; sigset_t mask; unsigned long msg_num; fd = open("/dev/swctrl_psu", O_RDWR); if (fd < 0) { printf("can't open %s\\n", PSU_DEVICE_NAME); return -1; } else printf("%s open success\\n", PSU_DEVICE_NAME); fcntl(fd, F_SETOWN, getpid()); Oflags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, Oflags | FASYNC); pthread_mutex_init(&mutex, 0); ret = ioctl(fd, READ_INIT_SYNC, &msg_num); if (0 == ret) { if (READ_SYNC_ACK == msg_num) printf("init sync success\\n"); else { printf(" init sync failed\\n"); return -1; } } else printf("ioctrl failed\\n"); signal(SIGIO, psu_signal_fun); while (1) { sleep(100); printf("wake up!\\n"); } return 0; }
1
#include <pthread.h> struct connections_chunk { void *data; int id; }; struct connections_buffer { struct connections_chunk *chunks; int chunks_count; pthread_mutex_t mutex; }; static int connections_get_index(struct connections_buffer *buffer, int id) { int lower = 0, upper = buffer->chunks_count - 1; while (lower <= upper) { int cur = (lower + upper) / 2; if (buffer->chunks[cur].id > id) upper = cur - 1; else if (buffer->chunks[cur].id < id) lower = cur + 1; else return cur; } printf("Not found connections chunk %d\\n", id); return -1; } struct connections_buffer* connections_new(void) { struct connections_buffer *buffer = malloc(sizeof(struct connections_buffer)); bzero(buffer, sizeof(struct connections_buffer)); pthread_mutex_init(&buffer->mutex, 0); return buffer; } void connections_free(struct connections_buffer *buffer) { pthread_mutex_lock(&buffer->mutex); if (buffer->chunks != 0) free(buffer->chunks); pthread_mutex_unlock(&buffer->mutex); pthread_mutex_destroy(&buffer->mutex); free(buffer); } void connections_add(struct connections_buffer *buffer, void *data, int id) { pthread_mutex_lock(&buffer->mutex); int lower = 0, upper = buffer->chunks_count - 1; while (lower <= upper) { int cur = (lower + upper) / 2; if (buffer->chunks[cur].id > id) upper = cur - 1; else if (buffer->chunks[cur].id < id) lower = cur + 1; else return; } buffer->chunks = realloc(buffer->chunks, (buffer->chunks_count + 1) * sizeof(struct connections_chunk)); buffer->chunks_count++; struct connections_chunk *chunk = 0; if (upper < 0) { memmove(buffer->chunks + 1, buffer->chunks, (buffer->chunks_count - 1) * sizeof(struct connections_chunk)); chunk = &buffer->chunks[0]; } else if (lower >= buffer->chunks_count) chunk = &buffer->chunks[buffer->chunks_count - 1]; else { memmove(buffer->chunks + lower + 1, buffer->chunks + lower, (buffer->chunks_count - lower - 1) * sizeof(struct connections_chunk)); chunk = &buffer->chunks[lower]; } bzero(chunk, sizeof(struct connections_chunk)); chunk->data = data; chunk->id = id; printf("Added connection %d\\n", id); pthread_mutex_unlock(&buffer->mutex); } void* connections_get(struct connections_buffer *buffer, int id) { pthread_mutex_lock(&buffer->mutex); void *data = 0; int index = connections_get_index(buffer, id); if (index != -1) data = buffer->chunks[index].data; pthread_mutex_unlock(&buffer->mutex); return data; } void connections_remove(struct connections_buffer *buffer, int id) { pthread_mutex_lock(&buffer->mutex); int index = connections_get_index(buffer, id); if (index == -1) { pthread_mutex_unlock(&buffer->mutex); return; } buffer->chunks_count--; if (buffer->chunks_count == 0) { free(buffer->chunks); buffer->chunks = 0; pthread_mutex_unlock(&buffer->mutex); return; } if (index != buffer->chunks_count) memcpy(buffer->chunks + index, buffer->chunks + index + 1, (buffer->chunks_count - index) * sizeof(struct connections_chunk)); buffer->chunks = realloc(buffer->chunks, buffer->chunks_count * sizeof(struct connections_chunk)); printf("Removed connection %d\\n", id); pthread_mutex_unlock(&buffer->mutex); }
0
#include <pthread.h> static pthread_mutex_t s_state_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t s_state_cond = PTHREAD_COND_INITIALIZER; static int s_port = -1; static const char * s_device_path = 0; static int s_device_socket = 0; static int s_closed = 0; static void usage(char *s) { fprintf(stderr, "usage: %s [-p <tcp port>] [-d /dev/tty_device]\\n", s); exit(-1); } static void waitForClose() { pthread_mutex_lock(&s_state_mutex); while (s_closed == 0) { pthread_cond_wait(&s_state_cond, &s_state_mutex); } pthread_mutex_unlock(&s_state_mutex); } static void onATReaderClosed() { LOGI("AT channel closed\\n"); at_close(); s_closed = 1; } static void onATTimeout() { LOGI("AT channel timeout; closing\\n"); at_close(); s_closed = 1; } static void * mainLoop(void *param) { int fd; int ret; LOGI("== entering mainLoop() -1"); AT_DUMP("== ", "entering mainLoop()", -1 ); at_set_on_reader_closed(onATReaderClosed); at_set_on_timeout(onATTimeout); for (;;) { fd = -1; while (fd < 0) { if (s_port > 0) { fd = socket_loopback_client(s_port, SOCK_STREAM); } else if (s_device_socket) { if (!strcmp(s_device_path, "/dev/socket/qemud")) { fd = socket_local_client( "qemud", ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM ); if (fd >= 0 ) { char answer[2]; if ( write(fd, "gsm", 3) != 3 || read(fd, answer, 2) != 2 || memcmp(answer, "OK", 2) != 0) { close(fd); fd = -1; } } } else fd = socket_local_client( s_device_path, ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM ); } else if (s_device_path != 0) { fd = open (s_device_path, O_RDWR); if ( fd >= 0 && !memcmp( s_device_path, "/dev/ttyS", 9 ) ) { struct termios ios; tcgetattr( fd, &ios ); ios.c_lflag = 0; tcsetattr( fd, TCSANOW, &ios ); LOGI("open device success"); }else { LOGI("open device failed"); } } if (fd < 0) { perror ("opening AT interface. retrying..."); sleep(10); } } s_closed = 0; ret = at_open(fd, 0); if (ret < 0) { LOGE ("AT error %d on at_open\\n", ret); return 0; } sleep(1); waitForClose(); LOGI("Re-opening after close"); } } int main (int argc, char **argv) { int ret; int fd = -1; int opt; while ( -1 != (opt = getopt(argc, argv, "p:d:"))) { switch (opt) { case 'p': s_port = atoi(optarg); if (s_port == 0) { usage(argv[0]); } LOGI("Opening loopback port %d\\n", s_port); break; case 'd': s_device_path = optarg; LOGI("Opening tty device %s\\n", s_device_path); break; case 's': s_device_path = optarg; s_device_socket = 1; LOGI("Opening socket %s\\n", s_device_path); break; default: usage(argv[0]); } } if (s_port < 0 && s_device_path == 0) { usage(argv[0]); } mainLoop(0); return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; printf("Starting inc_count(): thread %ld\\n", my_id); for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); printf("inc_count() get lock! thread: %ld\\n", my_id); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); count = 0; } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); printf("watch_count() get lock!\\n"); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1 = 1; long tt[20]; pthread_t threads[20]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); for (i = 0; i < 20; i++) { tt[i] = (long)(i + 2); pthread_create(&threads[i], &attr, inc_count, (void *)tt[i]); } for (i=0; i<20; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 20); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t *lockarray; static void lock_callback(int mode, int type, char *file, int line) { (void)file; (void)line; if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&(lockarray[type])); } else { pthread_mutex_unlock(&(lockarray[type])); } } static unsigned long thread_id(void) { unsigned long ret; ret=(unsigned long)pthread_self(); return(ret); } static void init_locks(void) { int i; lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); for (i=0; i<CRYPTO_num_locks(); i++) { pthread_mutex_init(&(lockarray[i]),0); } CRYPTO_set_id_callback((unsigned long (*)())thread_id); CRYPTO_set_locking_callback((void (*)())lock_callback); } static void kill_locks(void) { int i; CRYPTO_set_locking_callback(0); for (i=0; i<CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(lockarray[i])); OPENSSL_free(lockarray); } const char *urls[]= { "https://www.sf.net/", "https://www.openssl.org/", "https://www.sf.net/", "https://www.openssl.org/", }; static void *pull_one_url(void *url) { CURL *curl; curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_perform(curl); curl_easy_cleanup(curl); return 0; } int main(int argc, char **argv) { pthread_t tid[4]; int i; int error; (void)argc; (void)argv; init_locks(); for(i=0; i< 4; i++) { error = pthread_create(&tid[i], 0, pull_one_url, (void *)urls[i]); if(0 != error) fprintf(stderr, "Couldn't run thread number %d, errno %d\\n", i, error); else fprintf(stderr, "Thread %d, gets %s\\n", i, urls[i]); } for(i=0; i< 4; i++) { error = pthread_join(tid[i], 0); fprintf(stderr, "Thread %d terminated\\n", i); } kill_locks(); return 0; }
0
#include <pthread.h> int global_value = 0; pthread_mutex_t global_mutex = PTHREAD_MUTEX_INITIALIZER; void *race( void *ptr ) { if(!0) { pthread_mutex_lock( &global_mutex ); } int *id = (int *) ptr; global_value = *id; usleep(1); printf("%d=%d\\n", *id, global_value); if(!0) { pthread_mutex_unlock( &global_mutex ); } } int main() { pthread_t thread[20]; int ids[20]; int thread_value[20]; int i=0; printf("program iterujacy 0,0,0,0...\\n"); int value = 0; for(i=0; i<20; i++) { ids[i] = i+1; } for(i=0; i<20; i++) { thread_value[i] = pthread_create( &thread[i], 0, race, (void*) &ids[i]); } for(i=0; i<20; i++) { pthread_join( thread[i], 0); } for(i=0; i<20; i++) { } return 0; }
1
#include <pthread.h> void initLog(void); int pushLog(int,int); int popLog(int); void printLog(void); void freeLog(void); void* func_producer(void*); void* func_consumer(void*); struct THREAD_PARAMETERES{ int pid; }; pthread_attr_t attr; pthread_mutex_t mutex; sem_t sem_empty; sem_t sem_full; int* mylog; int main(int argc, char *argv[]){ initLog(); pthread_attr_init(&attr); pthread_mutex_init(&mutex, 0); int res; res = sem_init(&sem_empty, 0, 5);if(res==-1) printf("sem_init: sem_empty\\n"); res = sem_init(&sem_full,0,0);if(res==-1) printf("sem_init: sem_full\\n"); PP* prod_param[5]; for(int i=0;i<5;i++){ prod_param[i] = (PP*)malloc(sizeof(PP)); prod_param[i]->pid = i; } PP* cons_param[3]; for(int i=0;i<3;i++){ cons_param[i] = (PP*)malloc(sizeof(PP)); cons_param[i]->pid = i; } pthread_t producer[5]; pthread_t consumer[3]; for(int i=0;i<5;i++) pthread_create(producer+i,&attr,func_producer,(void*)(prod_param[i])); for(int i=0;i<3;i++) pthread_create(consumer+i,&attr,func_consumer,(void*)(cons_param[i])); for(int i=0;i<5;i++) pthread_join(producer[i],0); for(int i=0;i<3;i++) pthread_join(consumer[i],0); for(int i=0;i<5;i++) {free(prod_param[i]);prod_param[i]=0;} for(int i=0;i<3;i++) {free(cons_param[i]);cons_param[i]=0;} printLog(); freeLog(); exit(0); } void* func_producer(void* param){ for(int i=0;i<2;i++){ sem_wait(&sem_empty); pthread_mutex_lock(&mutex); int pid = ((PP*)param)->pid; printf("PRODUCER: cont: %d, ind: %d\\n", pid*(-1), pid); pushLog(pid,pid*10); pthread_mutex_unlock(&mutex); sem_post(&sem_full); } pthread_exit(0); } void* func_consumer(void* param){ for(int i=0;i<2;i++){ sem_wait(&sem_full); pthread_mutex_lock(&mutex); int pid = ((PP*)param)->pid; printf("CONSUMER: ind: %d\\n", pid); popLog(pid); pthread_mutex_unlock(&mutex); sem_post(&sem_empty); } pthread_exit(0); } void initLog(void){ mylog = (int*)malloc(sizeof(int)*5); for(int i=0;i<5;i++) mylog[i] = -1; } int pushLog(int cont, int ind){ mylog[ind] = cont; return 0; } int popLog(int ind){ mylog[ind] = -1; return 0; } void printLog(void){ for(int i=0;i<5;i++) printf("%d ",mylog[i]); printf("\\n"); } void freeLog(void){ free(mylog); mylog = 0; }
0
#include <pthread.h> int tickets=10; pthread_mutex_t mutex; pthread_cond_t cond; void* s_func( void* p) { long i=(long)p; while( 1) { pthread_mutex_lock( &mutex); if(tickets>0) { printf("i am windows %ld,tickets is %d\\n" ,i,tickets); tickets--; if( tickets==0) { pthread_cond_signal( &cond); } printf("i am windows %ld,sale a ticket,tickets is %d\\n" ,i,tickets); }else{ pthread_mutex_unlock(&mutex); pthread_exit( 0); } pthread_mutex_unlock(&mutex); } } void* set_func( void* p) { pthread_mutex_lock(&mutex); if( tickets>0) { pthread_cond_wait(&cond,&mutex); } tickets=10; pthread_mutex_unlock( &mutex); sleep( 1); pthread_exit( 0); } int main( ) { pthread_mutex_init( &mutex,0); pthread_cond_init( &cond,0); pthread_t sale[2],setticket; long i; for(i=0;i<2;i++) { pthread_create(&sale[i],0,s_func,( void*)i); } pthread_create( &setticket,0,set_func,0); for(i=0;i<2;i++) { pthread_join(sale[i],0); } pthread_join( setticket,0); pthread_mutex_destroy(&mutex); pthread_cond_destroy( &cond); return 0; }
1
#include <pthread.h> pthread_t pr[4]; pthread_mutex_t se[4]; pthread_mutex_t seEnd[4]; pthread_mutex_t seIndex; int pIndex = 0; int fIndex = 0; int mIndex = 15; int files[15] = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}; int lockTimes[4] = {0,3,4,5}; int file; int z = 0; void * print(void *arg){ pthread_mutex_lock(&seIndex); int i = pIndex++; pthread_mutex_unlock(&seIndex); printf("Start %d \\n",i ); while(fIndex<mIndex){ pthread_mutex_lock(&se[i]); file = files[fIndex]; pthread_mutex_lock(&seIndex); fIndex++; pthread_mutex_unlock(&seIndex); printf("=> Print %d file %d, time is: %ds.\\n",i,file,lockTimes[file]*100 ); int lockTime = z+lockTimes[file]; while(z<lockTime); pthread_mutex_unlock(&se[i]); } pthread_mutex_unlock(&seEnd[i]); } int main(int argc, char const *argv[]) { pthread_mutex_lock(&seEnd[0]); pthread_mutex_lock(&seEnd[1]); pthread_mutex_lock(&seEnd[2]); pthread_mutex_lock(&seEnd[3]); pthread_create(&pr[0],0,print,0); pthread_create(&pr[1],0,print,0); pthread_create(&pr[2],0,print,0); pthread_create(&pr[3],0,print,0); while(z<1000) { z++; } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int test_array [3][5]; int col_sums [3]; void* create_array(void*); void* sum_columns(void*); void print_array(void); int main(){ int sum_thread = 3; int total_sum = 0; pthread_t gen_thread; pthread_t sum_threads [3]; pthread_attr_t attr; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&gen_thread, &attr, create_array, 0); pthread_join(gen_thread, 0); for (int ti = 0; ti < sum_thread; ti++) { pthread_create(&sum_threads[ti], &attr, sum_columns, (void *) ti); } for (int ti = 0; ti < sum_thread; ti++) { pthread_join(sum_threads[ti], 0); } print_array(); for (int i = 0; i < 3; i++) { total_sum += col_sums[i]; } printf("\\nFinishing...\\n"); return 0; } void* create_array(void* arg) { srand(time(0)); pthread_mutex_lock(&mutex); for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { test_array[i][j] = (int)(rand() % 10); } } pthread_mutex_unlock(&mutex); return ((void *) 0); } void* sum_columns(void* arg) { int column_sum = 0; int column_idx = (int) arg; for (int i = 0; i < 5; i++) { column_sum += test_array[column_idx][i]; } pthread_mutex_lock(&mutex); col_sums[column_idx] = column_sum; pthread_mutex_unlock(&mutex); return ((void *) 0); } void print_array(void) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { printf ("%d ", test_array[j][i]); } printf("\\n"); } }
1
#include <pthread.h> pthread_mutex_t lock; int variableCompartidaSuma = 0; int elementosPitagoricos[4] = {1, 2, 3, 4}; void* sumarValor (void* parametro) { int posArray; posArray = (intptr_t) parametro; printf("Sumando posicion = %d \\n", posArray); pthread_mutex_lock(&lock); int aux = variableCompartidaSuma; int microseconds; srand (time(0)); microseconds = rand() % 1000 + 1; usleep(microseconds); aux = aux + elementosPitagoricos[posArray]; variableCompartidaSuma=aux; pthread_mutex_unlock(&lock); pthread_exit(0); } int main () { pthread_t threads[4]; pthread_mutex_init(&lock,0); int rc; int i; for( i=0; i < 4; i++ ){ printf("main() : creando thread %d \\n", i); rc = pthread_create(&threads[i], 0, sumarValor, (void *)(intptr_t) i); if (rc){ printf("Error:unable to create thread, %d \\n", rc); exit(-1); } } for(i = 0 ; i < 4 ; i++) { pthread_join(threads[i] , 0); } printf("El numero de la perfeccion es : %d \\n", variableCompartidaSuma); pthread_mutex_destroy(&lock); pthread_exit(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; 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> unsigned long long main_counter, counter[3]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_worker(void*); int main(int argc,char* argv[]) { int i, rtn, ch; pthread_t pthread_id[3] = {0}; int a = 0,b=1,c=2; pthread_create(&pthread_id[0],0,thread_worker,(void*)&a); pthread_create(&pthread_id[1],0,thread_worker,(void*)&b); pthread_create(&pthread_id[2],0,thread_worker,(void*)&c); do { unsigned long long sum = 0; pthread_mutex_lock(&mutex); for (i=0; i<3; i++) { sum += counter[i]; printf("%llu ", counter[i]); } printf("%llu/%llu", main_counter, sum); pthread_mutex_unlock(&mutex); }while ((ch = getchar()) != 'q'); return 0; } void* thread_worker(void* p) { int thread_num; thread_num = *(int*)p; for(;;) { pthread_mutex_lock(&mutex); counter[thread_num]++; main_counter++; pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> void wait(int); void down_forks(int, int); void *philosopher(void*); int food_on_table(); void get_fork(int, int, char*); pthread_mutex_t forks[5]; pthread_t phils[5]; pthread_mutex_t foodlock; int sleep_seconds = 0; int main(int argn, char **argv) { int i; if (argn == 2) sleep_seconds = atoi(argv[1]); pthread_mutex_init(&foodlock, 0); for (i = 0; i < 5; i++) pthread_mutex_init(&forks[i], 0); for (i = 0; i < 5; i++) pthread_create(&phils[i], 0, philosopher, (void *) i); for (i = 0; i < 5; i++) pthread_join(phils[i], 0); return 0; } void * philosopher(void *num) { int id; int left_fork, right_fork, f; id = (int) num; printf("Philosopher %d sitting down to dinner.\\n", id); right_fork = id; left_fork = id + 1; if (left_fork == 5) left_fork = 0; while (f = food_on_table()) { printf("Philosopher %d: get dish %d.\\n", id, f); for (;;) { pthread_mutex_lock(&forks[left_fork]); printf("Philosopher %d: got %s fork %d\\n", id, "left", left_fork); if (pthread_mutex_trylock(&forks[right_fork]) != EBUSY) { printf("Philosopher %d: got %s fork %d\\n", id, "right", right_fork); break; } else { printf("Philosopher %d: put %s fork %d (another was already taken)\\n", id, "left", left_fork); pthread_mutex_unlock(&forks[left_fork]); wait(f); continue; } } printf("Philosopher %d: eating.\\n", id); wait(f); down_forks(right_fork, left_fork); } printf("Philosopher %d is done eating.\\n", id); return (0); } void wait(int f) { usleep(30000 * (50 - f + 1)); } int food_on_table() { static int food = 50; int myfood; pthread_mutex_lock(&foodlock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock(&foodlock); return myfood; } void down_forks(int f1, int f2) { pthread_mutex_unlock(&forks[f1]); pthread_mutex_unlock(&forks[f2]); }
1
#include <pthread.h> pthread_barrier_t barrier; pthread_mutex_t consoleMutex; struct CalculateExpArgs { double value; unsigned int numberOfOperations; double result; }; void* CalculateExp(void* args) { struct CalculateExpArgs* expArgs = (struct CalculateExpArgs*)args; pthread_mutex_lock(&consoleMutex); printf("CalculateExp: arg = %f\\n", expArgs->value); pthread_mutex_unlock(&consoleMutex); double factorial = 1, power; expArgs->result = 1; for (unsigned int i = 0; i < expArgs->numberOfOperations; i++) { power = i + 1; factorial *= power; expArgs->result += pow(expArgs->value, power) / factorial; } pthread_mutex_lock(&consoleMutex); printf("CalculateExp: exp(arg) = %f\\n", expArgs->result); pthread_mutex_unlock(&consoleMutex); pthread_barrier_wait(&barrier); return 0; } struct CalculatePiArgs { unsigned int numberOfOperations; double result; }; void* CalculatePi(void* args) { struct CalculatePiArgs* piArgs = (struct CalculatePiArgs*)args; pthread_mutex_lock(&consoleMutex); printf("CalculatePi: ...\\n"); pthread_mutex_unlock(&consoleMutex); piArgs->result = 1; int numerator = 2, denominator = 1; int numeratorCounter = 0, denominatorCounter = 1; for (unsigned int i = 0; i < piArgs->numberOfOperations; i++) { if (numeratorCounter == 2) { numeratorCounter = 0; numerator += 2; } if (denominatorCounter == 2) { denominatorCounter = 0; denominator += 2; } numeratorCounter++; denominatorCounter++; piArgs->result *= ((double) numerator / (double) denominator); } piArgs->result *= 2; pthread_mutex_lock(&consoleMutex); printf("CalculatePi: pi = %f\\n", piArgs->result); pthread_mutex_unlock(&consoleMutex); pthread_barrier_wait(&barrier); return 0; } int main(int argc, const char * argv[]) { pthread_t threadExp; pthread_t threadPi; pthread_barrier_init(&barrier, 0, 2); pthread_mutex_init(&consoleMutex, 0); double x = 1; struct CalculateExpArgs expArgs; expArgs.value = (-pow(x, 2.)) / 2; expArgs.numberOfOperations = 100000; if (pthread_create(&threadExp, 0, &CalculateExp, &expArgs) == -1) { pthread_mutex_lock(&consoleMutex); printf("CalculateExp() thread launching failed."); pthread_mutex_unlock(&consoleMutex); return -1; } struct CalculatePiArgs piArgs; piArgs.numberOfOperations = 100000; if (pthread_create(&threadPi, 0, &CalculatePi, &piArgs) == -1) { pthread_mutex_lock(&consoleMutex); printf("CalculatePi() thread launching failed."); pthread_mutex_unlock(&consoleMutex); return -1; } pthread_join(threadExp, 0); pthread_join(threadPi, 0); pthread_barrier_destroy(&barrier); printf("f(x) = %f\\n", expArgs.result / sqrt(2 * piArgs.result)); return 0; }
0
#include <pthread.h> struct calltrace_rec { uint64_t type; uint64_t this_fn; uint64_t call_site; uint64_t timestamp; uint64_t pid; uint64_t tid; }; static int enable = 1; static FILE *fptr = 0; static uint64_t nrecords = 0; static pthread_mutex_t loglock = PTHREAD_MUTEX_INITIALIZER; void __cyg_profile_func_enter (void * this_fn, void * call_site) { struct calltrace_rec myrec; assert(pthread_mutex_lock(&loglock) == 0); if (enable) { if (nrecords > 200000) { fclose(fptr); fptr = 0; nrecords = 0; } if (fptr == 0) { int pathbuflen = 0; char *buf = 0, *path = 0; const char *dir = getenv("CALLTRACEDIR"); if (dir == 0) dir = "/tmp"; pathbuflen = strlen(dir) + 100; path = calloc(1, pathbuflen); assert(path != 0); snprintf(path, pathbuflen, "%s/calltrace-%u.log", dir, getpid()); fptr = fopen(path, "w"); assert(fptr != 0); free(path); path = 0; buf = (char *)malloc((1024 * 1024)); assert(buf != 0); setbuffer(fptr, buf, (1024 * 1024)); } myrec.type = 0x1; myrec.this_fn = (uint64_t)this_fn; myrec.call_site = (uint64_t)call_site; myrec.timestamp = (uint64_t) time(0); myrec.tid = (uint64_t)pthread_self(); myrec.pid = (uint64_t)getpid(); fwrite((void *)&myrec, sizeof(myrec), 1, fptr); nrecords++; } pthread_mutex_unlock(&loglock); } void __cyg_profile_func_exit (void * this_fn, void * call_site) { struct calltrace_rec myrec; assert(pthread_mutex_lock(&loglock) == 0); if (enable && fptr != 0) { myrec.type = 0x2; myrec.this_fn = (uint64_t)this_fn; myrec.call_site = (uint64_t)call_site; myrec.timestamp = (uint64_t) time(0); myrec.tid = (uint64_t)pthread_self(); myrec.pid = (uint64_t)getpid(); fwrite((void *)&myrec, sizeof(myrec), 1, fptr); nrecords++; } pthread_mutex_unlock(&loglock); } void calltrace_flush() { assert(pthread_mutex_lock(&loglock) == 0); if (fptr) fflush(fptr); pthread_mutex_unlock(&loglock); } void calltrace_enable() { assert(pthread_mutex_lock(&loglock) == 0); enable = 1; pthread_mutex_unlock(&loglock); } void calltrace_disable() { assert(pthread_mutex_lock(&loglock) == 0); enable = 0; if (fptr) fclose(fptr); fptr = 0; pthread_mutex_unlock(&loglock); }
1
#include <pthread.h> int pthread_kill_siginfo_np (pthread_t tid, siginfo_t si) { int sig = si.si_signo; if (sig < 0 || sig >= NSIG) return EINVAL; if (sig == 0) return 0; struct signal_state *ss = &__pthread_getid (tid)->ss; pthread_mutex_lock (&sig_lock); pthread_mutex_lock (&ss->lock); if (ss->sigwaiter && (ss->sigwaiter->signals & sigmask (si.si_signo))) { ss->sigwaiter->info = si; sigwaiter_unblock (ss->sigwaiter); return 0; } pthread_mutex_unlock (&sig_lock); if (ss->actions[sig - 1].sa_handler == (void *) SIG_IGN || (ss->actions[sig - 1].sa_handler == (void *) SIG_DFL && default_action (sig) == sig_ignore)) { pthread_mutex_unlock (&ss->lock); return 0; } if ((sigmask (sig) & ss->blocked)) { ss->pending |= sigmask (sig); pthread_mutex_unlock (&ss->lock); return 0; } if (pthread_self () == tid && (! (ss->actions[si.si_signo - 1].sa_flags & SA_ONSTACK) || (ss->stack.ss_flags & SS_DISABLE) || (ss->stack.ss_flags & SS_ONSTACK))) signal_dispatch (ss, &si); else signal_dispatch_lowlevel (ss, tid, si); return 0; }
0
#include <pthread.h> int gi = 1; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond; void *rabota(void *num){ long t_num; t_num = (long) num; pthread_mutex_lock(&mut); gi++; pthread_mutex_unlock(&mut); sleep (gi); printf("Поток %ld, выполнил полезную работу\\n", t_num); pthread_mutex_lock(&mut); if (gi != 1 + 3){ pthread_cond_wait(&cond, &mut); } else{ pthread_mutex_unlock(&mut); pthread_cond_broadcast(&cond); } } int main () { pthread_cond_init(&cond, 0); pthread_t threads[3]; int rc, t; for(t = 0; t < 3; t++) { printf("Создание потока%d\\n", t); rc = pthread_create(&threads[t], 0, rabota, (void*) t); if (rc) { printf("Ошибка создания потока is %d\\n", rc); exit(-1); } } for(t = 0; t < 3; t++) { pthread_join(threads[t], 0); printf("Поток %d завершен\\n", t); } return 0; }
1
#include <pthread.h> int _mode = 0; int nReaders = 0; sem_t _accessQueue; pthread_mutex_t _mutex; void readLock(){ pthread_mutex_lock(&_mutex); if(_mode == 0){ nReaders++; }else{ sem_wait(&_accessQueue); } pthread_mutex_unlock(&_mutex); } void readUnLock(){ pthread_mutex_lock(&_mutex); nReaders--; if(nReaders == 0 && _mode == 0){ sem_post(&_accessQueue); } pthread_mutex_unlock(&_mutex); } void writeLock(){ pthread_mutex_lock(&_mutex); if(nReaders == 0){ sem_wait(&_accessQueue); } pthread_mutex_unlock(&_mutex); } void writeUnLock(){ pthread_mutex_lock(&_mutex); sem_post(&_accessQueue); pthread_mutex_unlock(&_mutex); } int main(int argc, char *argv[]){ }
0
#include <pthread.h> static unsigned char bitmap[536870912]; static unsigned long *bstart; static unsigned long mapblocksize; static unsigned long root2; static int gnum_threads, sievebit = 2; static pthread_mutex_t sievemutex; static pthread_mutex_t *blockmutex; static unsigned long sieveblock = 0; static int iWantToPrint; void errExit(char *s) { perror(s); exit(-1); } int printPrimes(void) { unsigned long i, j, prinum = 0, num = 0; for (i = 0; i < 536870912; i++) for (j = 0; j < 8; j++, num++) if (!(bitmap[i] & 1<<j)) { if (iWantToPrint) fprintf(stdout, "%ld\\n", num); prinum++; } unsigned long long size = 536870912; size *= 8; if (iWantToPrint) fprintf(stderr, "%lu primes found below %llu.\\n", prinum, size); else fprintf(stdout, "%lu primes found below %llu.\\n", prinum, size); return 0; } int nextSieve() { sievebit++; for (; sieveblock < (root2+1)/8; sieveblock++) { for (; sievebit < 8; sievebit++) if (!(bitmap[sieveblock] & 1 << sievebit)) break; if (sievebit >= 8) sievebit = 0; else return 0; } return -1; } static void * third(void *arg) { int i; int localbit; unsigned long localblock, locsvadd, locblockadd, locbitadd; while (1) { pthread_mutex_lock(&sievemutex); if (nextSieve() == -1) { pthread_mutex_unlock(&sievemutex); break; } locsvadd = (sieveblock*8 + sievebit) * 2; locblockadd = locsvadd/8; locbitadd = locsvadd - locblockadd*8; localbit = sievebit + locbitadd; localblock = sieveblock + locblockadd; for (; localbit >= 8; localbit -= 8, localblock++); pthread_mutex_unlock(&sievemutex); for (i = 0; i < gnum_threads; i++) { pthread_mutex_lock(&blockmutex[i]); if (localblock >= bstart[i]) { while (localblock < bstart[i+1]) { bitmap[localblock] |= (1 << localbit); localblock += locblockadd; localbit += locbitadd; for (; localbit >= 8; localbit -= 8, localblock++); } } pthread_mutex_unlock(&blockmutex[i]); } } pthread_exit((void*) 0); } void sievemap_init() { unsigned long locsvadd, locblockadd, locbitadd, localbit, localblock; unsigned long root2blocks = (root2+1)/8; while (1) { if (nextSieve() == -1) break; locsvadd = (sieveblock * 8 + sievebit) * 2; locblockadd = locsvadd/8; locbitadd = locsvadd - locblockadd*8; localbit = sievebit + locbitadd; localblock = sieveblock + locblockadd; for (; localbit >= 8; localbit -= 8, localblock++); while (localblock < root2blocks) { bitmap[localblock] |= (1 << localbit); localblock += locblockadd; localbit += locbitadd; for (; localbit >= 8; localbit -= 8, localblock++); } } sieveblock = 0; sievebit = 2; return; } void init_gbm() { int i; for (i = 0; i < 536870912; i++) bitmap[i] = 0x55; bitmap[0] = 0x53; return; } void initialize_globals(void) { root2 = (unsigned int) sqrt((double) 536870912 * 8); init_gbm(); sievemap_init(); mapblocksize = 536870912 / gnum_threads; if (mapblocksize * 8 < root2) errExit("Too many threads"); int i; bstart = malloc((gnum_threads+1) * sizeof(long)); if (bstart == 0) errExit("out of memory for bitmap divider array"); for (i = 0; i < gnum_threads; i++) bstart[i] = (mapblocksize + 1) * i; bstart[gnum_threads] = 536870912; return; } int beginThreading(int num_threads) { gnum_threads = num_threads; long i; void *status; initialize_globals(); if (pthread_mutex_init(&sievemutex, 0) != 0) errExit("mutex initialization error"); blockmutex = malloc(num_threads * sizeof(pthread_mutex_t)); if (blockmutex == 0) errExit("not enough memory for mutex array"); for (i = 0; i < num_threads; i++) if (pthread_mutex_init(&blockmutex[i], 0) != 0) errExit("mutex initialization error"); pthread_t *svthr = malloc(num_threads * sizeof(pthread_t)); if (svthr == 0) errExit("not enough memory for thread array"); for (i = 0; i < num_threads; i++) if (pthread_create(&svthr[i], 0, third, (void*) i) != 0) errExit("couldn't make thread"); for (i = 0; i < num_threads; i++) if (pthread_join(svthr[i], &status) != 0) errExit("couldn't join thread"); printPrimes(); for (i = 0; i < num_threads; i++) if (pthread_mutex_destroy(&blockmutex[i]) != 0) errExit("couldn't destroy mutex"); if (pthread_mutex_destroy(&sievemutex) != 0) errExit("couldn't destroy mutex"); free(bstart); free(blockmutex); free(svthr); return 0; } int main(int argc, char **argv) { int num_threads; switch(argc) { case 0: case 1: printf("Defaulting to one thread.\\n"); beginThreading(1); return 0; case 2: case 3: if (argc == 3) iWantToPrint = 1; if ((num_threads = atoi(argv[1])) > 0) beginThreading(num_threads); else printf("%s is not a positive integer.\\n", argv[1]); return 0; default: printf("Too many arguments.\\n"); return 0; } }
1
#include <pthread.h> pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; FILE * flog = 0; int def_priv=0; const char * priorities[3]= { "FATAL", "ERROR", "WARNING" }; int Log_init(int priority, const char * file_name) { pthread_mutex_lock(&log_mutex); def_priv=priority; if (flog) fclose(flog); flog=fopen(file_name,"a"); pthread_mutex_unlock(&log_mutex); if (flog == 0) return -1; else return 0; } void Log(int priority, const char * fmt,...) { char buf[300]; size_t l; time_t t; va_list v; if (priority < 0 || priority > def_priv || flog == 0) return; pthread_mutex_lock(&log_mutex); time(&t); ctime_r(&t,buf); l=strlen(buf)-1; if (priority >= 3) snprintf(buf+l,300 -l-1,": PRIORITY: %d: ",priority); else snprintf(buf+l,300 -l-1,": %s: ",priorities[priority]); fprintf(flog,"%s",buf); __builtin_va_start((v)); vfprintf(flog,fmt,v); ; pthread_mutex_unlock(&log_mutex); } void Log_close(void) { fclose(flog); flog=0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int cliSock; void serverSalir(){ close(cliSock); exit(0); } int isValidIpAddress(char *ipAddress) { struct sockaddr_in sa; int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr)); if(result==0){ puts("Error. La ip no es valida\\n"); return 0; } else return 1; } int esPuertoValido(int puerto){ if(puerto<1024 || puerto>65535){ puts("Error. El puerto debe ser un entero entre 1025 y 65535\\n"); return 0; } } void validarParam(char * ip, int puerto){ if(isValidIpAddress(ip)==0 || esPuertoValido(puerto) == 0){ puts("Error en la validacion de parametros.\\n"); puts("La ejecucion debe ser del siguiente estilo: ./cliente {ip/hostname} {puerto server} {nickname}"); printf(". Ejemplo de ejecucion: ./cliente localhost 3500 tomas "); exit(0); } } int hostnameToIp(char * hostname , char* ip){ struct hostent *he; struct in_addr **addr_list; int i; if ( (he = gethostbyname( hostname ) ) == 0) { herror("gethostbyname"); return 1; } addr_list = (struct in_addr **) he->h_addr_list; for(i = 0; addr_list[i] != 0; i++) { strcpy(ip , inet_ntoa(*addr_list[i]) ); return 0; } return 1; } void *autorizacion (void * sock){ int bytesRecv; int serverSock = *((int *)sock); char rta [4]="no"; puts("Esperando autorizacion del server para entrar a la sala. Por favor, espere."); while (strcmp(rta,"si")!=0) { if((bytesRecv = recv(serverSock,rta,3,0)) > 0) { rta[bytesRecv] = '\\0'; } } puts("\\nBienvenido a la sala. Ingrese un mensaje:\\n"); pthread_mutex_unlock(&mutex); bzero(rta,sizeof(rta)); fflush(stdout); pthread_exit(0); } void *threadRecvMensaje(void *sock){ int serverSock = *((int *)sock); char mensaje[1024]; int bytesRecv; while((bytesRecv = recv(serverSock,mensaje,1024,0)) > 0) { mensaje[bytesRecv] = '\\0'; if(strcmp(mensaje,"SALIR_DEL_SERVER")==0){ serverSalir(); } fputs(mensaje,stdout); bzero(mensaje,sizeof(mensaje)); fflush(stdout); } } int main(int argc, char *argv[]) { struct sockaddr_in serverAddr; int serverSock,serverAddr_size,nPuerto,bytesRecv; pthread_t sendt,recvt,aut; char mensaje[1024]; char hostname[128],serverIp[128]; char res[1100]; char ip[INET_ADDRSTRLEN]; char nickname[64]; if(argc != 4) { puts("Error. La ejecucion debe ser del siguiente estilo: ./cliente {ip/hostname} {puerto server} {nickname}"); printf(". Ejemplo de ejecucion: ./cliente localhost 3500 tomas "); exit(1); } nPuerto = atoi(argv[2]); strcpy(hostname,argv[1]); if(hostnameToIp(hostname,serverIp)==1){ strcpy(serverIp,hostname); } validarParam(serverIp,nPuerto); strcpy(nickname,argv[3]); cliSock = socket(AF_INET,SOCK_STREAM,0); memset(serverAddr.sin_zero,'\\0',sizeof(serverAddr.sin_zero)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(nPuerto); serverAddr.sin_addr.s_addr = inet_addr(serverIp); if(connect(cliSock,(struct sockaddr *)&serverAddr,sizeof(serverAddr)) < 0) { perror("Cliente: error. Conexion no establecida"); exit(1); } inet_ntop(AF_INET, (struct sockaddr *)&serverAddr, ip, INET_ADDRSTRLEN); pthread_create(&aut,0,autorizacion,&cliSock); pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex); pthread_create(&recvt,0,threadRecvMensaje,&cliSock); fflush(stdin); strcpy(nickname,argv[3]); while(fgets(mensaje,1024,stdin) > 0) { strcpy(res,nickname); strcat(res,":"); strcat(res,mensaje); bytesRecv = write(cliSock,res,strlen(res)); if(bytesRecv < 0) { perror("Error: mensaje no enviado"); exit(1); } bzero(mensaje,sizeof(mensaje)); bzero(res,sizeof(res)); } pthread_join(recvt,0); close(cliSock); pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> char name[20]; char comment[50]; char type[10]; int dimension; char wtype[10]; } InstanceData; void printTour(int*); void printMatrix(); double** readEuc2D(char*); double tourCost(int*); int* nearestNeighbour(); void swap(); void* SimulatedAnnealing(); InstanceData ins; double **matrix; int *bestTour; double temperature; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char **argv) { int i; void *status; pthread_t *threads; threads = (pthread_t *)malloc(sizeof(pthread_t)*5); temperature = 100000; matrix = readEuc2D(argv[1]); bestTour = (int *)malloc(sizeof(int)*ins.dimension); for (i = 0; i < ins.dimension;i++) bestTour[i] = i; pthread_mutex_init(&mutex,0); for (i = 0; i < 5; i++) { if (pthread_create(&threads[i], 0, SimulatedAnnealing, (void *)i)) { exit(-1); } } for (i = 0; i < 5; i++) { if (pthread_join(threads[i], &status)) { exit(-1); } } pthread_mutex_destroy(&mutex); printf("Best Distance: %lf\\n", tourCost(bestTour)); return 0; } void printTour(int *tour) { int i; printf("TOUR: "); for (i = 0; i < ins.dimension; i++) printf("%d ", tour[i]); printf("\\n"); } void printMatrix() { int i,j; for (i = 0; i < ins.dimension; i++) { for (j = 0; j < ins.dimension; j++) printf("%lf ", matrix[i][j]); printf("\\n"); } } double** readEuc2D(char* name) { FILE *file; double **matrix; double **coord; int i,j; file = fopen(name, "r"); fscanf(file, "NAME: %[^\\n]s", ins.name); fscanf(file, "\\nTYPE: TSP%[^\\n]s", ins.type); fscanf(file, "\\nCOMMENT: %[^\\n]s", ins.comment); fscanf(file, "\\nDIMENSION: %d",&ins.dimension); fscanf(file, "\\nEDGE_WEIGHT_TYPE: %[^\\n]s", ins.wtype); fscanf(file, "\\nNODE_COORD_SECTION"); coord = (double **)malloc(ins.dimension*sizeof(double*)); for(i=0;i<ins.dimension;i++) coord[i] = (double*) malloc(2*sizeof(double)); for(i=0;i<ins.dimension;i++) fscanf(file, "\\n %*[^ ] %lf %lf", &coord[i][0], &coord[i][1]); matrix = (double **)malloc(sizeof(double*)*(ins.dimension)); for (i = 0; i < ins.dimension; i++) matrix[i] = (double *)malloc(sizeof(double)*(ins.dimension)); for (i = 0; i < ins.dimension; i++) { for (j = i + 1 ; j < ins.dimension; j++) { matrix[i][j] = sqrt(pow(coord[i][0] - coord[j][0],2) + pow(coord[i][1] - coord[j][1],2)); matrix[j][i] = matrix[i][j]; } } free(coord); return matrix; } double tourCost(int *tour) { int i; double value = 0.0; for (i = 0; i < ins.dimension - 1; i++) value += matrix[tour[i]][tour[i+1]]; return value + matrix[tour[0]][tour[ins.dimension-1]]; } int* nearestNeighbour() { int *tour; int *visited; double nearestDistance; int nearestIndex; int i,j; visited = (int*) malloc(ins.dimension*sizeof(int)); tour = (int*) malloc(ins.dimension*sizeof(int)); for(i=0;i<ins.dimension;i++) visited[i] = 0; int start; pthread_mutex_lock(&mutex); start = rand()%ins.dimension; pthread_mutex_unlock(&mutex); visited[start] = 1; tour[0] = start; for(i=1;i<ins.dimension;i++){ nearestDistance = FLT_MAX; nearestIndex = 0; for(j=0;j<ins.dimension;j++){ if(!visited[j] && matrix[tour[i-1]][j] < nearestDistance){ nearestDistance = matrix[tour[i-1]][j]; nearestIndex = j; } } tour[i] = nearestIndex; visited[nearestIndex] = 1; } free(visited); return tour; } void swap(int *currentTour, int *nextTour) { int i,auxiliar; for (i = 0; i < ins.dimension; i++) nextTour[i] = currentTour[i]; pthread_mutex_lock(&mutex); int first = (rand() % (ins.dimension - 1)) + 1; int second = (rand() % (ins.dimension - 1)) + 1; pthread_mutex_unlock(&mutex); auxiliar = nextTour[first]; nextTour[first] = nextTour[second]; nextTour[second] = auxiliar; } void* SimulatedAnnealing(void *id) { int *currentTour; int *nextTour; double distance; double delta; int i; long seed; seed = time(0); srand(seed+(int)id*12345); currentTour = nearestNeighbour(); distance = tourCost(currentTour); nextTour = (int *)malloc(sizeof(int)*ins.dimension); while (temperature > 0.00001) { swap(currentTour, nextTour); delta = tourCost(nextTour) - distance; if (((delta < 0) || (distance > 0)) && (exp(-delta/temperature) > (double)rand()/32767)) { for (i = 0; i < ins.dimension; i++) currentTour[i] = nextTour[i]; distance = delta + distance; } pthread_mutex_lock(&mutex); temperature *= 0.9999; pthread_mutex_unlock(&mutex); } pthread_mutex_lock(&mutex); if (tourCost(bestTour) > tourCost(currentTour)) { for (i = 0; i < ins.dimension; i++) bestTour[i] = currentTour[i]; } pthread_mutex_unlock(&mutex); return(0); }
0
#include <pthread.h> buffer_t buffer[5]; int buffer_index; pthread_mutex_t buffer_mutex; sem_t full_sem; sem_t empty_sem; void insertbuffer(buffer_t value) { if (buffer_index < 5) { buffer[buffer_index++] = value; } else { printf("Buffer overflow\\n"); } } buffer_t dequeuebuffer() { if (buffer_index > 0) { return buffer[--buffer_index]; } else { printf("Buffer underflow\\n"); } return 0; } void *producer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { sleep(rand() % 10); value = rand() % 100; sem_wait(&full_sem); pthread_mutex_lock(&buffer_mutex); insertbuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&empty_sem); printf("Producer %d added %d to buffer\\n", thread_numb, value); } pthread_exit(0); } void *consumer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { sem_wait(&empty_sem); pthread_mutex_lock(&buffer_mutex); value = dequeuebuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&full_sem); printf("Consumer %d dequeue %d from buffer\\n", thread_numb, value); } pthread_exit(0); } int main(int argc, int **argv) { buffer_index = 0; pthread_mutex_init(&buffer_mutex, 0); sem_init(&full_sem,0,5); sem_init(&empty_sem, 0, 0); pthread_t thread[4]; int thread_numb[4]; int i; for (i = 0; i < 4; ) { thread_numb[i] = i; pthread_create(thread + i, 0, producer,thread_numb + i); i++; thread_numb[i] = i; pthread_create(&thread[i], 0, consumer, &thread_numb[i]); i++; } for (i = 0; i < 4; i++) pthread_join(thread[i], 0); pthread_mutex_destroy(&buffer_mutex); sem_destroy(&full_sem); sem_destroy(&empty_sem); return 0; }
1
#include <pthread.h> { void *(*process) (void *arg); void *arg; struct worker *next; } CThread_worker; { pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t *threadid; int max_thread_num; int cur_queue_size; } CThread_pool; int pool_add_worker (void *(*process) (void *arg), void *arg); void *thread_routine (void *arg); static CThread_pool *pool = 0; void pool_init (int max_thread_num) { pool = (CThread_pool *) malloc (sizeof (CThread_pool)); pthread_mutex_init (&(pool->queue_lock), 0); pthread_cond_init (&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); int i = 0; for (i = 0; i < max_thread_num; i++) { pthread_create (&(pool->threadid[i]), 0, thread_routine, 0); } } int pool_add_worker (void *(*process) (void *arg), void *arg) { CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock (&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if (member != 0) { while (member->next != 0) member = member->next; member->next = newworker; } else { pool->queue_head = newworker; } assert (pool->queue_head != 0); pool->cur_queue_size++; pthread_mutex_unlock (&(pool->queue_lock)); pthread_cond_signal (&(pool->queue_ready)); return 0; } int pool_destroy () { if (pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast (&(pool->queue_ready)); int i; for (i = 0; i < pool->max_thread_num; i++) pthread_join (pool->threadid[i], 0); free (pool->threadid); CThread_worker *head = 0; while (pool->queue_head != 0) { head = pool->queue_head; pool->queue_head = pool->queue_head->next; free (head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free (pool); pool=0; return 0; } void * thread_routine (void *arg) { printf ("starting thread 0x%x/n", pthread_self ()); while (1) { pthread_mutex_lock (&(pool->queue_lock)); while (pool->cur_queue_size == 0 && !pool->shutdown) { printf ("thread 0x%x is waiting/n", pthread_self ()); pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); } if (pool->shutdown) { pthread_mutex_unlock (&(pool->queue_lock)); printf ("thread 0x%x will exit/n", pthread_self ()); pthread_exit (0); } printf ("thread 0x%x is starting to work/n", pthread_self ()); assert (pool->cur_queue_size != 0); assert (pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock (&(pool->queue_lock)); (*(worker->process)) (worker->arg); free (worker); worker = 0; } pthread_exit (0); } void *myprocess (void *arg) { printf ("threadid is 0x%x, working on task %d/n", pthread_self (),*(int *) arg); sleep (1); return 0; } int main (int argc, char **argv) { pool_init (3); int *workingnum = (int *) malloc (sizeof (int) * 10); int i; for (i = 0; i < 10; i++) { workingnum[i] = i; pool_add_worker (myprocess, &workingnum[i]); } sleep (5); pool_destroy (); free (workingnum); return 0; }
0