text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int producer(void *args); int consumer(void *args); pthread_mutex_t mutex; sem_t product; sem_t warehouse; char buffer[8][10]; int bp=0; int main(int argc,char **args) { pthread_mutex_init(&mutex,0); sem_init(&warehouse,0,8); sem_init(&product,0,0); int clone_flag,arg,retval; char *stack; clone_flag = CLONE_VM|CLONE_SIGHAND|CLONE_FS|CLONE_FILES; int i; for(i=0;i<2;i++) { arg=i; stack = (char *) malloc(4096); retval = clone((void *)producer,&(stack[4095]),clone_flag,(void*)&arg); stack = (char *) malloc(4096); retval = clone((void *)consumer,&(stack[4095]),clone_flag,(void*)&arg); sleep(1); } sleep(60); exit(1); } int producer(void *args) { int id= *((int *)args); int i; for (i = 0; i < 10; ++i) { sleep(i+1); sem_wait(&warehouse); pthread_mutex_lock(&mutex); if(id==0) { strcpy(buffer[bp],"aaa\\0"); } else { strcpy(buffer[bp],"bbb\\0"); } bp++; printf("producer %d produce %s in %d \\n",id,buffer[bp-1],bp-1); pthread_mutex_unlock(&mutex); sem_post(&product); } printf("producer %d is over!\\n",id ); } int consumer(void *args) { int id=*((int *)args); int i; for(i=0;i<10;i++) { sleep(10-i); sem_wait(&product); pthread_mutex_lock(&mutex); bp--; printf("consumer %d get %s in %d\\n",id,buffer[bp],bp ); strcpy(buffer[bp],"zzz\\0"); pthread_mutex_unlock(&mutex); sem_post(&warehouse); } printf("consumer %d is over !\\n",id); }
1
#include <pthread.h> static void arruma_ordem (int id); static void checa_terceiro (); int sorteia_vel (int id) { int i, eq, ret, v; if (g_modo == 'u') return 1; if (cic[id].volta <= 0) return 0; eq = id / g_n; pthread_mutex_lock (&mutex_ord[eq]); v = cic[id].volta; for (i = cic[id].pos_eq - 1; i >= 0 && cic[ord[eq][i]].volta == v; i--) if (cic[ord[eq][i]].proibe) { cic[id].proibe = FALSE; pthread_mutex_unlock (&mutex_ord[eq]); return 0; } pthread_mutex_unlock (&mutex_ord[eq]); ret = (((double) rand () / 32767) < .5); cic[id].proibe = !(ret | cic[id].proibe); return ret; } int atualiza_pos (int id) { int npos = (cic[id].pos + cic[id].vel) % g_d; int nmeio = cic[id].meio; int ret = TRUE, eq, faixa, oid, oeq; if (cic[id].meio && cic[id].vel == 0) { nmeio = FALSE; npos = (cic[id].pos + 1) % g_d; } else if (!cic[id].meio && cic[id].vel == 0) nmeio = TRUE; pthread_mutex_lock (&mutex_pista); if (pista[npos][0] != -1 && pista[npos][1] != -1) if (npos != cic[id].pos) ret = FALSE; pthread_mutex_unlock (&mutex_pista); if (!ret) return ret; eq = id / g_n; pthread_mutex_lock (&mutex_pista); faixa = (pista[cic[id].pos][1] == id); oid = pista[cic[id].pos][!faixa]; pthread_mutex_unlock (&mutex_pista); if (oid != -1 && npos != cic[id].pos) { oeq = oid / g_n; pthread_mutex_lock (&mutex_ord[eq]); if (oeq == eq && cic[id].pos_eq == cic[oid].pos_eq + 1 && cic[id].volta == cic[oid].volta) { ord[eq][cic[id].pos_eq] = oid; cic[id].pos_eq--; ord[eq][cic[oid].pos_eq] = id; cic[oid].pos_eq++; } else if (oeq != eq) { checa_terceiro (id, oid); } pthread_mutex_unlock (&mutex_ord[eq]); } cic[id].pos = npos; cic[id].meio = nmeio; cic[id].acc += 1 + cic[id].vel; return ret; } void atualiza_volta (int id, int t) { int eq = 0; if (cic[id].pos == cic[id].largada && !cic[id].meio) { cic[id].volta++; cic[id].vel = sorteia_vel (id); eq = id / g_n; pthread_mutex_lock (&mutex_ord[eq]); if (ord[eq][2] == id) { printf ("Terceiro colocado da equipe %c esta na volta %d (%d u.t.)\\n" "1: ciclista %d\\n" "2: ciclista %d\\n" "3: ciclista %d\\n", 'A' + eq, cic[id].volta, t, ord[eq][0], ord[eq][1], ord[eq][2]); } pthread_mutex_unlock (&mutex_ord[eq]); } } void atualiza_pista (int ant, int id) { int prox = cic[id].pos; int faixa; pthread_mutex_lock (&mutex_pista); faixa = (pista[ant][1] == id); pista[ant][faixa] = -1; faixa = (pista[prox][1] == -1); pista[prox][faixa] = id; pthread_mutex_unlock (&mutex_pista); } void sincroniza (int saindo) { static int iter = 1; pthread_mutex_lock (&mutex_sinc); if (g_correndo != 1) { if (saindo) g_correndo--; g_chegou = (g_chegou + !saindo) % g_correndo; if (g_chegou == 0) { if (g_debug && !g_acabou) imprime_debug (iter++); if (g_acabou) g_ultra3 = TRUE; pthread_cond_broadcast (&barreira); } else pthread_cond_wait (&barreira, &mutex_sinc); } pthread_mutex_unlock (&mutex_sinc); } int quebra (int id) { int ret; int v = cic[id].volta; pthread_mutex_lock (&mutex_q); if (v == 0) ret = FALSE; else if (v % 4 != 0) ret = FALSE; else if (quebrado[v]) ret = FALSE; else if (restante[id / g_n] < 4) ret = FALSE; else if ((double) rand () / 32767 <= 0.1) { quebrado[v] = TRUE; restante[id / g_n]--; cic[id].quebrado = TRUE; arruma_ordem (id); ret = TRUE; printf ("QUEBROU: Ciclista %d na volta %d na posicao %d\\n", id, cic[id].volta, cic[id].pos); } else ret = FALSE; pthread_mutex_unlock (&mutex_q); return ret; } void remove_cic (int id) { int faixa; pthread_mutex_lock (&mutex_pista); faixa = (pista[cic[id].pos][1] == id); pista[cic[id].pos][faixa] = -1; pthread_mutex_unlock (&mutex_pista); } static void checa_terceiro (int id, int oid) { if (cic[id].pos_eq == 2 && cic[oid].pos_eq == 2 && cic[id].acc > cic[oid].acc) { if (id / g_n == 0) g_acabou = A_VITORIA; else g_acabou = B_VITORIA; } } static void arruma_ordem (int id) { int i, eq; eq = id / g_n; pthread_mutex_lock (&mutex_ord[eq]); for (i = cic[id].pos_eq + 1; i < g_n; i++) { ord[eq][i-1] = ord[eq][i]; cic[ord[eq][i-1]].pos_eq--; } ord[eq][g_n-1] = id; cic[id].pos_eq = g_n-1; pthread_mutex_unlock (&mutex_ord[eq]); }
0
#include <pthread.h> const int NrProd = 3, NrCons = 2; const int BufLen = 6; int in = 0, out = 0; sem_t empty, full; pthread_mutex_t mutex; int producerID = 0, consumerID = 0; void handler(int signo) { printf("Exit program.\\n"); exit(0); } void *producerFunc(void *arg) { int id = producerID++; int i = 0; int *buf = 0; buf = arg; while (1) { sleep(2); sem_wait(&empty); pthread_mutex_lock(&mutex); buf[in] = 1; printf("Producer %d produces %d:", id, in); for (i = 0; i < BufLen; ++i) if (buf[i]) printf(" %d", i); printf("\\n"); in = (in + 1) % BufLen; pthread_mutex_unlock(&mutex); sem_post(&full); } } void *consumerFunc(void * arg) { int id = consumerID++; int i = 0; int *buf = 0; buf = arg; while (1) { sleep(2); sem_wait(&full); pthread_mutex_lock(&mutex); buf[out] = 0; printf("Consumer %d consumes %d:", id, out); for (i = 0; i < BufLen; ++i) if (buf[i]) printf(" %d", i); printf("\\n"); out = (out + 1) % BufLen; pthread_mutex_unlock(&mutex); sem_post(&empty); } } int main() { int rc = 0; int i = 0; int *buf = 0; buf = malloc(BufLen * 4); if (!buf) { printf("can't malloc\\n"); exit(1); } if (signal(SIGINT, handler) == SIG_ERR) { printf("Signal error.\\n"); exit(1); } rc = sem_init(&empty, 0, BufLen); if (rc != 0) { printf("Init empty error %d, errno: %d %s\\n", rc, errno, strerror(errno)); exit(1); } if (sem_init(&full, 0, 0) != 0) { printf("Init full error.\\n"); exit(1); } pthread_t producer[NrProd]; for (i = 0; i < NrProd; ++i) { if (pthread_create(&producer[i], 0, producerFunc, buf) != 0) { printf("Creating producer %d error.\\n", i); exit(1); } } pthread_t consumer[NrCons]; for (i = 0; i < NrCons; ++i) { if (pthread_create(&consumer[i], 0, consumerFunc, buf) != 0) { printf("Creating consumer %d error.\\n", i); exit(1); } } printf("main(), wait for thread join\\n"); for (i = 0; i < NrProd; ++i) pthread_join(producer[i], 0); for (i = 0; i < NrCons; ++i) pthread_join(consumer[i], 0); printf("main(), done\\n"); return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; static void * thread_helper(void *arg) { void (*testfunc)(void) = arg; testfunc(); pthread_mutex_lock(&mutex); pthread_cond_broadcast(&cond1); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond2, &mutex); pthread_mutex_unlock(&mutex); return 0; } int main(void) { void *dso; void (*testfunc)(void); pthread_t thread; dso = dlopen("libh_helper_dso3.so", RTLD_LAZY); if (dso == 0) errx(1, "%s", dlerror()); testfunc = dlsym(dso, "testfunc"); if (testfunc == 0) errx(1, "%s", dlerror()); pthread_mutex_lock(&mutex); if (pthread_create(&thread, 0, thread_helper, testfunc)) err(1, "pthread_create"); pthread_cond_wait(&cond1, &mutex); pthread_mutex_unlock(&mutex); printf("before dlclose\\n"); dlclose(dso); printf("after dlclose\\n"); dso = dlopen("libh_helper_dso3.so", RTLD_LAZY); if (dso == 0) errx(1, "%s", dlerror()); dlclose(dso); pthread_mutex_lock(&mutex); pthread_cond_signal(&cond2); pthread_mutex_unlock(&mutex); if (pthread_join(thread, 0)) err(1, "pthread_join"); return 0; }
0
#include <pthread.h> int event_filter(const struct inotify_event *event) { int n = 0; if ((event->mask) & IN_IGNORED) n = 1; if (!((event->mask) & IN_ISDIR) && ((event->mask) & IN_CREATE)) n = 1; if (strchr((event->name), '.') == (event->name)) n = 1; if (strchr((event->name), '~') == ((event->name) + strlen(event->name) - 1)) n = 1; if (strcmp((event->name), "4913") == 0) n = 1; return n; } void add_watch_for_new_dir(const struct inotify_event *event) { struct watch_entry *watch = search_watch_in_watch_list(start_watch_list, event->wd); char* parent_loc = watch->loc; char* dir_path = calloc(strlen(parent_loc) + (event->len) + 1, sizeof(char)); strcpy(dir_path, parent_loc); strcat(dir_path, "/"); strcat(dir_path, event->name); int mode = IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MOVE; int w = inotify_add_watch(inotify_instance, dir_path, mode); struct watch_entry *new_watch = create_watch_entry(dir_path, w); pthread_mutex_lock(&mutex_watch); add_watch_entry_to_list(&start_watch_list, new_watch); pthread_mutex_unlock(&mutex_watch); free(dir_path); } void* monitor_file_system_thread(void* arg) { analyse_dir_to_monitor("/home/kevin/Projekte/Legion/TestEnv"); char buf[4096] ; const struct inotify_event *event; ssize_t len; char *ptr; int changes = 0; while(1) { len = read(inotify_instance, buf, sizeof(buf)); if (len <= 0) { sd_journal_print(LOG_ERR, "couldn't read event!\\n"); exit(1); } for (ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) { event = (const struct inotify_event *) ptr; if (event_filter(event) == 1) continue; if((event->mask & IN_ISDIR) && (event->mask & IN_CREATE)) { add_watch_for_new_dir(event); } add_event_to_list(&curr_event_list, event); changes = 1; } if((changes != 0)) { pthread_cond_signal(&cond_mutex_2); changes = 0; } } }
1
#include <pthread.h> static int glob = 0; static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mtx3 = PTHREAD_MUTEX_INITIALIZER; static void * threadFunc1(void *arg) { pthread_mutex_lock(&mtx1); if(glob%2==0){ pthread_mutex_lock(&mtx2); glob += 1; printf("in t1 glob = %d\\n", glob); pthread_mutex_unlock(&mtx2); pthread_mutex_unlock(&mtx1); } else{ pthread_mutex_lock(&mtx3); glob += 1; printf("in t1 glob = %d\\n", glob); pthread_mutex_unlock(&mtx3); pthread_mutex_unlock(&mtx1); } return 0; } static void * threadFunc2(void *arg) { pthread_mutex_lock(&mtx2); pthread_mutex_lock(&mtx1); glob += 1; printf("in t2 glob = %d\\n", glob); pthread_mutex_unlock(&mtx1); pthread_mutex_unlock(&mtx2); return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int loops,s; s = pthread_create(&t1, 0, threadFunc1, 0); s = pthread_create(&t2, 0, threadFunc2, 0); s = pthread_join(t1, 0); s = pthread_join(t2, 0); printf("glob = %d\\n", glob); return 0; }
0
#include <pthread.h> void handle_error(const char *file, int lineno, const char *msg) { fprintf(stderr, "** %s:%d %s\\n", file, lineno, msg); ERR_print_errors_fp(stderr); } static pthread_mutex_t *mutex_buf = 0; static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&(mutex_buf[n])); else pthread_mutex_unlock(&(mutex_buf[n])); } static unsigned long id_function(void) { return ((unsigned long) pthread_self( )); } int openssl_lck_setup(void) { int i; mutex_buf = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); if (!mutex_buf) return 0; for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_init(&(mutex_buf[i]), 0); CRYPTO_set_id_callback(id_function); CRYPTO_set_locking_callback(locking_function); return 1; } int openssl_lck_cleanup(void) { int i; if (!mutex_buf) return 0; CRYPTO_set_id_callback(0); CRYPTO_set_locking_callback(0); for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(mutex_buf[i])); free(mutex_buf); mutex_buf = 0; return 1; }
1
#include <pthread.h> pthread_mutex_t sharedElementMutex; pthread_cond_t canConsumeCondition; int canConsume = 0; int sharedElement = 0; int done = 0; void *theThread(void *parm){ int rc; printf("Consumer Thread %u: Entered\\n", pthread_self()); rc = pthread_mutex_lock(&sharedElementMutex); assert(!rc); while (!done) { while (!canConsume) { printf("Consumer Thread %u: Wait for data to be produced\\n", pthread_self()); rc = pthread_cond_wait(&canConsumeCondition, &sharedElementMutex); if (rc) { printf("Consumer Thread %u: condwait failed, rc=%d\\n", pthread_self(), rc); pthread_mutex_unlock(&sharedElementMutex); exit(1); } if(done){ break; } } if(done){ printf("Consumer thread %u: signaled to exit gracefuly. exit loop\\n", pthread_self()); break; } printf("Consumer thread %u: Found data! hooray\\n", pthread_self()); sharedElement--; if (sharedElement==0){ canConsume=0; } } printf("Consumer Thread %u: All done\\n",pthread_self()); rc = pthread_mutex_unlock(&sharedElementMutex); assert(!rc); return 0; } int main(int argc, char **argv){ pthread_t thread[2]; int rc = 0; int elementsToConsume = 4; int i; rc = pthread_mutex_init(&sharedElementMutex, 0); assert(rc==0); rc = pthread_cond_init(&canConsumeCondition, 0); assert(rc==0); printf("Create/start threads\\n"); for (i=0; i <2; i++) { rc = pthread_create(&thread[i], 0, theThread, 0); assert(!rc); } sleep(2); while (elementsToConsume--) { printf("Producer: 'Get' data\\n"); rc = pthread_mutex_lock(&sharedElementMutex); assert(!rc); printf("Producer: Make element shared and notify consumer\\n"); sharedElement++; canConsume=1; rc = pthread_cond_signal(&canConsumeCondition); if (rc) { pthread_mutex_unlock(&sharedElementMutex); printf("Producer: Failed to wake up consumer, rc=%d. Exiting\\n", rc); exit(1); } printf("Producer: Unlock shared data and flag (elementsToConsume=%d)\\n", elementsToConsume); rc = pthread_mutex_unlock(&sharedElementMutex); assert(!rc); sleep(1); } printf("Wait for the threads to complete, and release their resources\\n"); sleep(1); rc = pthread_mutex_lock(&sharedElementMutex); assert(!rc); done = 1; rc = pthread_mutex_unlock(&sharedElementMutex); assert(!rc); for (i=0; i <2; i++) { rc = pthread_mutex_lock(&sharedElementMutex); assert(!rc); pthread_cond_signal(&canConsumeCondition); rc = pthread_mutex_unlock(&sharedElementMutex); assert(!rc); } sleep(2); printf("Clean up\\n"); pthread_mutex_destroy(&sharedElementMutex); pthread_cond_destroy(&canConsumeCondition); printf("Main completed\\n"); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for( i=0; i<((400)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_error(); } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t number_mutex1; int globalnumber1 = 10; int globalnumber2 = 5; void thread2(void *arg); void thread1(void *arg); int main(void) { int status; pthread_t thid1,thid2; pthread_mutex_init(& number_mutex1,PTHREAD_MUTEX_TIMED_NP); if(pthread_create(&thid1,0,(void *)thread1,0) != 0){ printf("thid1 create failed\\n"); } if(pthread_create(&thid2,0,(void *)thread2,0) != 0){ printf("thid2 create failed\\n"); } pthread_join(thid1,(void *)&status); pthread_join(thid2,(void *)&status); return 0; } void thread2(void *arg) { int temp=0; sleep(2); pthread_mutex_lock(& number_mutex1); globalnumber2++; temp=globalnumber2; pthread_mutex_unlock(& number_mutex1); printf("i am thread2,my temp=%d\\n",temp); pthread_exit(0); } void thread1(void *arg) { pthread_mutex_lock(& number_mutex1); printf("i am thread1,my globalnumber=%d\\n",globalnumber1); globalnumber1++; sleep(5); pthread_mutex_unlock(& number_mutex1); pthread_exit(0); }
0
#include <pthread.h> double sum=0.0, a[1000000]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, start, *mytid, end; double mysum=0.0; mytid = (int *) tid; start = (*mytid * 1000000 / 8); end = start + 1000000 / 8; printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1); for (i=start; i < end ; i++) { a[i] = i * 1.0; mysum = mysum + a[i]; } pthread_mutex_lock (&sum_mutex); sum = sum + mysum; pthread_mutex_unlock (&sum_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, start, tids[8]; pthread_t threads[8]; pthread_attr_t attr; pthread_mutex_init(&sum_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<8; i++) pthread_create(&threads[i], &attr, do_work, (void *)(&i)); for (i=0; i<8; i++) { pthread_join(threads[i], 0); } printf ("Done. Sum= %e \\n", sum); sum=0.0; for (i=0;i<1000000;i++){ a[i] = i*1.0; sum = sum + a[i]; } printf("Check Sum= %e\\n",sum); pthread_attr_destroy(&attr); pthread_mutex_destroy(&sum_mutex); pthread_exit (0); }
1
#include <pthread.h> extern void do_work (); int thread_flag; pthread_mutex_t thread_flag_mutex; void initialize_flag () { pthread_mutex_init (&thread_flag_mutex, 0); thread_flag = 0; } void* thread_function (void* thread_arg) { while (1) { int flag_is_set; pthread_mutex_lock (&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock (&thread_flag_mutex); if (flag_is_set) do_work (); } return 0; } void set_thread_flag (int flag_value) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock (&thread_flag_mutex); }
0
#include <pthread.h> pthread_mutex_t varLock = PTHREAD_MUTEX_INITIALIZER; int var = 0; int id; int value; } thread_info; void *threadFunc(void *info) { thread_info *INFO = (thread_info*) info; printf("Sou a thread %d. Meu valor é: %d\\n", (int)INFO->id, INFO->value); int local = 0; for (size_t i = 0; i < 5; i++) local++; pthread_mutex_lock(&varLock); printf("var_antes = %d\\n", var); var += local; printf("var_depois = %d\\n", var); pthread_mutex_unlock(&varLock); } int main(int argc, char const *argv[]) { pthread_t THREADS[3]; thread_info *threads = calloc((int) 3, sizeof(thread_info)); for (size_t i = 0; i < 3; i++) { threads[i].id = i; threads[i].value = 10 * i; pthread_create(&THREADS[i], 0, threadFunc, &threads[i]); } for (size_t i = 0; i < 3; i++) pthread_join(&THREADS[i], 0); pthread_exit(0); return 0; }
1
#include <pthread.h> void mux_2_alusrca(void *not_used){ pthread_barrier_wait(&threads_creation); while(1) { pthread_mutex_lock(&control_sign); if (!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait, &control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } if((( (separa_ALUSrcA & cs.value) >> ALUSrcA_POS) & 0x01) == 0) mux_alusrca_buffer.value = pc; else mux_alusrca_buffer.value = a_value; pthread_mutex_lock(&mux_alusrca_result); mux_alusrca_buffer.isUpdated = 1; pthread_cond_signal(&mux_alusrca_execution_wait); pthread_mutex_unlock(&mux_alusrca_result); pthread_barrier_wait(&current_cycle); mux_alusrca_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
0
#include <pthread.h> pthread_t t[2]; pthread_mutex_t lock; int i; int number; int *retval; void die(int re, const char * msg) { if (re != 0) { perror(msg); } } void *func1(void * arg) { printf("the func1 thread %s\\n", (char *) arg); for (i = 0; i < 10; i++) { printf("the number = %d\\n", number); pthread_mutex_lock(&lock); number++; pthread_mutex_unlock(&lock); sleep(2); } pthread_exit(retval); return 0; } void *func2(void * arg) { printf("the func2 thread %s\\n", (char *) arg); for (i = 0; i < 10; i++) { printf("the number = %d\\n", number); pthread_mutex_lock(&lock); number++; pthread_mutex_unlock(&lock); sleep(3); } pthread_exit(retval); return 0; } void thread_create() { memset(&t, 0, sizeof(t)); int re = pthread_create(&t[0], 0, func1, "first thread"); die(re, "the first thread create error\\n"); re = pthread_create(&t[1], 0, func2, "second thread"); die(re, "the second thread create error\\n"); } void thread_wait() { if (t[0] != 0) { pthread_join(t[0], 0); } if (t[1] != 0) { pthread_join(t[1], 0); } }
1
#include <pthread.h> FILE* MF_LOG_FILE; void mf_logger_open(const char* path) { if(path == 0) { log_warn("Log path is not specific"); path = mf_default_log_path; } MF_LOG_FILE = fopen(path, "w"); if(MF_LOG_FILE == 0) { log_err("File open failed"); exit(0); } pthread_mutex_init(&log_mutex, 0); } void mf_write_log(char* msg) { pthread_mutex_lock(&log_mutex); if(unlikely(msg == 0)) { log_warn("Log Msg is null"); } char* t = get_asctime(); if(fprintf(MF_LOG_FILE, "[%s]:%s\\n", t, msg) < 0) { log_warn("Log write error"); } pthread_mutex_unlock(&log_mutex); } void mf_write_socket_log(char* msg, int socketfd) { pthread_mutex_lock(&log_mutex); if(msg == 0) { log_warn("\\nLog Msg is null"); } char* t = get_asctime(); if(fprintf(MF_LOG_FILE, "[%s]:<Socket: %d> %s\\n", t, socketfd, msg) < 0) { log_warn("Socket log write error"); } pthread_mutex_unlock(&log_mutex); } void mf_logger_close() { fclose(MF_LOG_FILE); }
0
#include <pthread.h> int shared_variable; int waiting_readers; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t read_sig = PTHREAD_COND_INITIALIZER; pthread_cond_t write_sig = PTHREAD_COND_INITIALIZER; int resource_counter; void *reader(void *arg); void *writer(void *arg); int main(int argc, char *argv[]) { int i, j; int reader_num[4]; int writer_num[4]; pthread_t rt[4]; pthread_t wt[4]; resource_counter = 0; waiting_readers = 0; for(i = 0; i < 4; i++) { j = i; reader_num[j] = j; pthread_create(&rt[j], 0, reader, &reader_num[j]); } for(i = 0; i < 4; i++) { j = i; writer_num[j] = j; pthread_create(&wt[j], 0, writer, &writer_num[j]); } for(i = 0; i < 4; i++) { j = i; pthread_join(rt[j], 0); } for(i = 0; i < 4; i++) { j = i; pthread_join(wt[j], 0); } printf("End of reader-writer program!\\n"); return 0; } void *reader(void *arg) { int thread_id = *((int *) arg); int i; for(i = 0; i < 5; i++){ usleep(1000 * (random() % 4 + 4)); pthread_mutex_lock(&m); waiting_readers++; while(resource_counter < 0) { pthread_cond_wait(&read_sig, &m); } waiting_readers--; resource_counter++; pthread_mutex_unlock(&m); printf("Reader %d shared variable: %d\\n", thread_id, shared_variable); pthread_mutex_lock(&m); resource_counter--; if (resource_counter == 0) { pthread_cond_broadcast(&write_sig); } pthread_mutex_unlock(&m); } pthread_exit(0); } void *writer(void *arg) { int thread_id = *((int *) arg); int i; for(i = 0; i < 5; i++){ usleep(1000 * (random() % 4 + 4)); pthread_mutex_lock(&m); while(resource_counter != 0) { pthread_cond_wait(&write_sig, &m); } resource_counter = -1; pthread_mutex_unlock(&m); shared_variable = thread_id << 1; printf("Writer %d writing %d\\n", thread_id, shared_variable); pthread_mutex_lock(&m); resource_counter = 0; if(waiting_readers > 0) { printf("waiting_readers %d\\n", waiting_readers); pthread_cond_broadcast(&read_sig); } else { pthread_cond_signal(&write_sig); } pthread_mutex_unlock(&m); } pthread_exit(0); }
1
#include <pthread.h> void init_gbl(int status, int imgCtoW_th, int imgWtoC_th, int saturation) { pthread_mutex_init(&g_stInfrad_ctl.mutex, 0); g_stInfrad_ctl.imgCtoW_th = imgCtoW_th; g_stInfrad_ctl.imgWtoC_th = imgWtoC_th; g_stInfrad_ctl.status = status; g_stInfrad_ctl.img_saturation = saturation; return; } int getImgCtoW() { int ret; pthread_mutex_lock(&g_stInfrad_ctl.mutex); ret = g_stInfrad_ctl.imgCtoW_th; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); return ret; } int getImgWtoC() { int ret; pthread_mutex_lock(&g_stInfrad_ctl.mutex); ret = g_stInfrad_ctl.imgWtoC_th; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); return ret; } int getInfradStatue() { int ret; pthread_mutex_lock(&g_stInfrad_ctl.mutex); ret = g_stInfrad_ctl.status; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); return ret; } int getImg_saturation() { int ret; pthread_mutex_lock(&g_stInfrad_ctl.mutex); ret = g_stInfrad_ctl.img_saturation; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); return ret; } void set_imgCtoW(int imgCtoW) { pthread_mutex_lock(&g_stInfrad_ctl.mutex); g_stInfrad_ctl.imgCtoW_th = imgCtoW; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); } void set_imgWtoC(int imgWtoC) { pthread_mutex_lock(&g_stInfrad_ctl.mutex); g_stInfrad_ctl.imgWtoC_th = imgWtoC; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); } void set_infradstatus(int status) { pthread_mutex_lock(&g_stInfrad_ctl.mutex); g_stInfrad_ctl.status = status; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); } void set_Img_saturation(int saturation) { pthread_mutex_lock(&g_stInfrad_ctl.mutex); g_stInfrad_ctl.img_saturation = saturation; pthread_mutex_unlock(&g_stInfrad_ctl.mutex); }
0
#include <pthread.h> pthread_mutex_t mtx; pthread_cond_t cnd; } pmtx_t; void *Mutex_Init() { pmtx_t *pmtx = malloc(sizeof(pmtx_t)); int ret = pthread_mutex_init(&pmtx->mtx, 0); if (ret) { DEBUG("%s (%i) :: CreateMutex error (%d) !\\n", __func__, 36, ret); return 0; } return pmtx; } void Mutex_Close(void *arg) { pmtx_t *pmtx = (pmtx_t *)arg; pthread_mutex_destroy(&pmtx->mtx); free(pmtx); } void Mutex_Lock(void *arg) { pmtx_t *pmtx = (pmtx_t *)arg; pthread_mutex_lock(&pmtx->mtx); } void Mutex_Unlock(void *arg) { pmtx_t *pmtx = (pmtx_t *)arg; pthread_mutex_unlock(&pmtx->mtx); } void Mutex_SPause(void *arg) { Mutex_Lock(arg); Mutex_Lock(arg); Mutex_Unlock(arg); } void Mutex_Pause(void *arg) { pmtx_t *pmtx = (pmtx_t *)arg; pthread_cond_wait(&pmtx->cnd, &pmtx->mtx); Mutex_Unlock(arg); } void Mutex_Resume(void *arg) { pmtx_t *pmtx = (pmtx_t *)arg; Mutex_Lock(arg); pthread_cond_signal(&pmtx->cnd); Mutex_Unlock(arg); }
1
#include <pthread.h> pthread_t fid[1],cid[20]; pthread_mutex_t cpu=PTHREAD_MUTEX_INITIALIZER,s[20]; int num; int remain; int state; }pcb; int remain; int index; }temp; pcb thread[20],nThread[20]; temp pcbIns[20]; int total=0; int first=0; int waitTime=0; void insertionSort(n){ int j=1; for(j=1;j<n;j++){ int key=pcbIns[j].remain; int i=j-1; while((i>=0)&&(pcbIns[i].remain>key)){ pcbIns[i+1].remain=pcbIns[i].remain; int tempIdx=pcbIns[i+1].index; pcbIns[i+1].index=pcbIns[i].index; pcbIns[i].index=tempIdx; i--; } pcbIns[i+1].remain=key; } } void* child(void* vargp){ int i = *(int*)vargp; pthread_mutex_lock(&s[i]); pthread_mutex_lock(&cpu); waitTime+=total; while(nThread[i].remain>0){ printf("ThreadId is:%d Round:%d Remain:%d\\n",nThread[i].num,total,nThread[i].remain); total++; nThread[i].remain--; } pthread_mutex_unlock(&cpu); pthread_mutex_unlock(&s[i]); } void* father(void* vargp){ srand(time(0)); int i=0; int it1=0; for(i=0;i<20;i++){ pthread_mutex_lock(&s[i]); thread[i].num=i; thread[i].remain=rand()%5+1; thread[i].state=0; pcbIns[i].remain=thread[i].remain; pcbIns[i].index=i; } for(i=0;i<20;i++){ thread[i].state=1; pthread_mutex_unlock(&s[i]); } insertionSort(20); first=pcbIns[0].index; for(it1=0;it1<20;it1++){ nThread[it1]=thread[pcbIns[it1].index]; } int inum[20]; for(it1=0;it1<20;it1++){ inum[it1]=it1; } for(it1=0;it1<20;it1++){ pthread_create(&cid[it1],0,child,(void*)(&inum[it1])); sleep(1); } for(i=0;i<20;i++){ pthread_join(cid[i],0); } printf("\\nAverage WaitTime = %f s\\n",waitTime*1.0/20); } int main(){ int i=0,j=0; for(j=0;j<20;j++){ s[j]=cpu; } pthread_create(&fid[i],0,father,(void*)(&i)); pthread_join(fid[i],0); return 0; }
0
#include <pthread.h> int main(int argc, char *argv[]) { int fd = 0, zero = 0, i = 0; int *addr = 0; int nloops = 0; pid_t cpid = 0; pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t *p_mutex; pthread_mutexattr_t mattr; if(argc != 2) { printf("usage: %s <loop number>\\n", argv[0]); return -1; } nloops = atoi(argv[1]); fd = open("foo.out", O_RDWR|O_CREAT, 0644); if(fd < 0) { perror("open file fail"); return -1; } write(fd, &zero, sizeof(zero)); write(fd, &init_mutex, sizeof(init_mutex)); addr = mmap(0, sizeof(int) + sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(addr == 0) { perror("mmap fail"); return -1; } close(fd); p_mutex = (pthread_mutex_t*) (addr + 1); pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(p_mutex, &mattr); setbuf(stdout, 0); if((cpid = fork()) < 0) { perror("fork fail"); exit(-1); } else if(cpid == 0) { for(i = 0; i < nloops; i++) { pthread_mutex_lock(p_mutex); (*addr)++; pthread_mutex_unlock(p_mutex); } exit(0); } for(i = 0; i < nloops; i++) { pthread_mutex_lock(p_mutex); (*addr)++; pthread_mutex_unlock(p_mutex); } wait(0); exit(0); }
1
#include <pthread.h> pthread_mutex_t x,wsem; pthread_t tid; int readcount; void intialize() { pthread_mutex_init(&x,0); pthread_mutex_init(&wsem,0); readcount=0; } void * reader (void * param) { int waittime; waittime = rand() % 5; printf("\\nReader is trying to enter"); pthread_mutex_lock(&x); readcount++; if(readcount==1) pthread_mutex_lock(&wsem); printf("\\n%d Reader is inside ",readcount); pthread_mutex_unlock(&x); sleep(waittime); pthread_mutex_lock(&x); readcount--; if(readcount==0) pthread_mutex_unlock(&wsem); pthread_mutex_unlock(&x); printf("\\nReader is Leaving"); } void * writer (void * param) { int waittime; waittime=rand() % 3; printf("\\nWriter is trying to enter"); pthread_mutex_lock(&wsem); printf("\\nWrite has entered"); sleep(waittime); pthread_mutex_unlock(&wsem); printf("\\nWriter is leaving"); sleep(30); exit(0); } int main() { int n1,n2,i; printf("\\nEnter the no of readers: "); scanf("%d",&n1); printf("\\nEnter the no of writers: "); scanf("%d",&n2); for(i=0;i<n1;i++) pthread_create(&tid,0,reader,0); for(i=0;i<n2;i++) pthread_create(&tid,0,writer,0); sleep(30); exit(0); }
0
#include <pthread.h> int make_listen(int port); void handle_connection(FILE* fin, FILE* fout); int remove_trailing_whitespace(char* buf); static pthread_mutex_t mutex; static pthread_cond_t condvar; static int n_connection_threads; void* connection_thread(void* arg) { FILE* f = (FILE*) arg; pthread_mutex_lock(&mutex); ++n_connection_threads; pthread_mutex_unlock(&mutex); pthread_detach(pthread_self()); handle_connection(f, f); fclose(f); pthread_mutex_lock(&mutex); --n_connection_threads; pthread_cond_signal(&condvar); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char** argv) { int port = 6168; if (argc >= 2) { port = strtol(argv[1], 0, 0); assert(port > 0 && port <= 65535); } int fd = make_listen(port); pthread_mutex_init(&mutex, 0); pthread_cond_init(&condvar, 0); while (1) { int cfd = accept(fd, 0, 0); if (cfd < 0) { perror("accept"); exit(1); } pthread_mutex_lock(&mutex); while (n_connection_threads > 100) { pthread_cond_wait(&condvar, &mutex); } pthread_mutex_unlock(&mutex); pthread_t t; FILE* f = fdopen(cfd, "a+"); setvbuf(f, 0, _IONBF, 0); int r = pthread_create(&t, 0, connection_thread, (void*) f); if (r != 0) { perror("pthread_create"); exit(1); } } } void handle_connection(FILE* fin, FILE* fout) { char buf[1024]; while (fgets(buf, 1024, fin)) if (remove_trailing_whitespace(buf)) { struct servent* service = getservbyname(buf, "tcp"); int port = service ? ntohs(service->s_port) : 0; fprintf(fout, "%s,%d\\n", buf, port); } if (ferror(fin)) perror("read"); } int make_listen(int port) { int fd = socket(AF_INET, SOCK_STREAM, 0); assert(fd >= 0); int r = fcntl(fd, F_SETFD, FD_CLOEXEC); assert(r >= 0); int yes = 1; r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); assert(r >= 0); struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = INADDR_ANY; r = bind(fd, (struct sockaddr*) &address, sizeof(address)); assert(r >= 0); r = listen(fd, 100); assert(r >= 0); return fd; } int remove_trailing_whitespace(char* buf) { int len = strlen(buf); while (len > 0 && isspace((unsigned char) buf[len - 1])) { --len; buf[len] = 0; } return len; }
1
#include <pthread.h> static int matrice_a[100][100]; static int matrice_b[100][100]; static int matrice_c[100][100]; static pthread_mutex_t mutex_matrice_mul; static void init(void) { int i, j; for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { matrice_a[i][j] = matrice_b[i][j] = random() % 100000; } } } static void *process(void *arg) { uintptr_t offset; long i, start, end, k, j; long sum; offset = (uintptr_t) arg; start = offset * (100/10); end = start + (100/10); for (i = start; i < end; i++) { for (j = 0; j < 100; j++) { sum = 0; for (k = 0; k < 100; k++) { sum += matrice_a[i][k] * matrice_b[k][j]; } pthread_mutex_lock(&mutex_matrice_mul); matrice_c[i][j] = sum; pthread_mutex_unlock(&mutex_matrice_mul); } } pthread_exit(0); } static void print_matrice(void) { int i, j; for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { printf("%d ", matrice_c[i][j]); } printf("\\n"); } } int main(void) { uintptr_t i; pthread_t threads[10]; init(); pthread_mutex_init(&mutex_matrice_mul, 0); for (i = 0; i < 10; i++) pthread_create(&threads[i], 0, process, (void *) i); for (i = 0; i < 10; i++) pthread_join(threads[i], 0); print_matrice(); pthread_mutex_destroy(&mutex_matrice_mul); exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex_personas[10]; pthread_mutex_t mutex[10][3]; int personas[10]; int capacidad_salas[10][3]; void *fila(void *); void capacidad(int, int, int); int main() { pthread_t taquillas[10][3]; int i, j; srand((int)time(0)); for (i = 0; i < 10; i++) { for (j = 0; j < 3; j++) { int *arg = malloc(sizeof(*arg)); *arg = i; pthread_create(&taquillas[i][j], 0, fila, arg); } } for (i = 0; i < 10; i++) { for (j = 0; j < 3; j++) { pthread_join(taquillas[i][j], 0); } } return 0; } void *fila(void *c) { int i = *((int *)c); while (150 > personas[i]) { pthread_mutex_lock(&mutex_personas[i]); int p = (rand() % 10) + 1; int sala = rand() % 3; if (sala == 0) { capacidad(sala, p, i); } else if (sala == 1) { capacidad(sala, p, i); } else if (sala == 2) { capacidad(sala, p, i); } else { printf("Algo salio mal :S\\n"); } pthread_mutex_unlock(&mutex_personas[i]); } printf("Complejo %d lleno\\n", i); free(c); pthread_exit(0); } void capacidad(int s, int p, int i) { pthread_mutex_lock(&mutex[i][s]); if (50 >= (p + capacidad_salas[i][s])) { capacidad_salas[i][s] += p; personas[i] += p; printf("Entraron %d personas en la sala %d, en el complejo %d\\n", p, s, i); printf("se encuentran ahora %d personas en la sala %d del complejo %d\\n", capacidad_salas[i][s], s, i); } else { printf("Lo sentimos, capacidad llena en la sala %d del complejo %d, hay %d " "personas\\n", s, i, capacidad_salas[i][s]); } pthread_mutex_unlock(&mutex[i][s]); }
1
#include <pthread.h> const char* noCon = "NO_CONN"; void resetCon(int index){ pthread_mutex_lock(&connection_mutex); connections[index].status = NOCONN; strcpy(connections[index].nickname,noCon); strcpy(connections[index].hostname,noCon); strcpy(connections[index].realname,noCon); connections[index].sockfd = 999999; pthread_mutex_unlock(&connection_mutex); } int setCon(int fd, char* nick, char* host, char* real){ pthread_mutex_lock(&connection_mutex); int idx = -1; for(int i=0; i< MAXCLIENTS; i++){ if(idx < 0){ if(connections[i].status == NOCONN){ idx = i; } } } if(idx >= 0){ connections[idx].status = CONN; strcpy(connections[idx].nickname, nick); strcpy(connections[idx].hostname, host); strcpy(connections[idx].realname, real); connections[idx].sockfd = fd; time(&connections[idx].time_joined); } pthread_mutex_unlock(&connection_mutex); return idx; } int findConnFD(int fd){ int idx = -1; pthread_mutex_lock(&connection_mutex); int i; for( i=0; i<MAXCLIENTS;i++){ if(idx < 0){ if(connections[i].sockfd == fd){ idx = i; } } } pthread_mutex_unlock(&connection_mutex); return idx; } void broadcast(char* msg, int index){ pthread_mutex_lock(&connection_mutex); int i; for(i=0;i<MAXCLIENTS;i++){ if(connections[i].status == CONN && index != i){ Writen(connections[i].sockfd,msg, strlen(msg)); } } pthread_mutex_unlock(&connection_mutex); } int findNickName(char* nickname){ int idx = -1; pthread_mutex_lock(&connection_mutex); int i; for( i=0; i<MAXCLIENTS;i++){ if(idx < 0){ if(strcmp(connections[i].nickname, nickname) == 0){ idx = i; } } } pthread_mutex_unlock(&connection_mutex); return idx; }
0
#include <pthread.h> struct header_t { size_t size; unsigned freemem; struct header_t *next; }; struct header_t *head = 0, *lst = 0; pthread_mutex_t global_malloc_lock; struct header_t *get_free_block(size_t size) { struct header_t *curr = head; while(curr) { if (curr->freemem && curr->size >= size) return curr; curr = curr->next; } return 0; } void myfree(void *block) { struct header_t *header, *tmp; if (!block) return; pthread_mutex_lock(&global_malloc_lock); header = (struct header_t*)block - 1; if ((char*)block + header->size == sbrk(0)) { if (head == lst) { head = lst = 0; } else { tmp = head; while (tmp) { if(tmp->next == lst) { tmp->next = 0; lst = tmp; } tmp = tmp->next; } } sbrk(0 - header->size - sizeof(struct header_t)); pthread_mutex_unlock(&global_malloc_lock); return; } header->freemem = 1; pthread_mutex_unlock(&global_malloc_lock); } void *mymalloc(size_t size) { size_t total_size; void *block; struct header_t *header; if (!size) return 0; pthread_mutex_lock(&global_malloc_lock); header = get_free_block(size); if (header) { header->freemem = 0; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } total_size = sizeof(struct header_t) + size; block = sbrk(total_size); if (block == (void*) -1) { pthread_mutex_unlock(&global_malloc_lock); return 0; } header = block; header->size = size; header->freemem = 0; header->next = 0; if (!head) head = header; if (lst) lst->next = header; lst = header; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } void *mycalloc(size_t num, size_t nsize) { size_t size; void *block; if (!num || !nsize) return 0; size = num * nsize; if (nsize != size / num) return 0; block = mymalloc(size); if (!block) return 0; memset(block, 0, size); return block; } void *myrealloc(void *block, size_t size) { struct header_t *header; void *ret; if (!block || !size) return mymalloc(size); header = (struct header_t*)block - 1; if (header->size >= size) return block; ret = mymalloc(size); if (ret) { memcpy(ret, block, header->size); myfree(block); } return ret; }
1
#include <pthread.h> pthread_mutex_t *global_lock; int main(int argc, char *argv[]) { global_lock = mmap(0, sizeof(*global_lock), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); pid_t pid = fork(); int k = 1000000; if (pid > 0) { struct timespec nStart, nEnd, nTotal; struct timeval uStart, uEnd, uTotal; clock_gettime(CLOCK_REALTIME, &nStart); gettimeofday(&uStart, 0); for (int i = 0 ; i < k ; i++) { pthread_mutex_lock(global_lock); pthread_mutex_unlock(global_lock); } clock_gettime(CLOCK_REALTIME, &nEnd); gettimeofday(&uEnd, 0); if ((nEnd.tv_nsec - nStart.tv_nsec) < 0) { nTotal.tv_sec = nEnd.tv_sec - nStart.tv_sec - 1; nTotal.tv_nsec = 1000000000 + nEnd.tv_nsec - nStart.tv_nsec; } else { nTotal.tv_sec = nEnd.tv_sec - nStart.tv_sec; nTotal.tv_nsec = nEnd.tv_nsec - nStart.tv_nsec; } if ((uEnd.tv_usec - uStart.tv_usec) < 0) { uTotal.tv_sec = uEnd.tv_sec - uStart.tv_sec - 1; uTotal.tv_usec = 1000000 + uEnd.tv_sec - uStart.tv_usec; } else { uTotal.tv_sec = uEnd.tv_sec - uStart.tv_sec; uTotal.tv_usec = uEnd.tv_usec - uStart.tv_usec; } long mTotal = uTotal.tv_usec / 1000; printf("second=%ld\\n", nTotal.tv_sec); printf("millisecond=%ld\\n", mTotal); printf("microsecond=%ld\\n", uTotal.tv_usec); printf("nanosecond=%ld\\n", nTotal.tv_nsec); printf("\\n"); } else if (pid == 0) { for (int i = 0 ; i < k ; i++) { pthread_mutex_unlock(global_lock); pthread_mutex_unlock(global_lock); } } return 0; }
0
#include <pthread.h> pthread_mutex_t lock2; int main(int argc, char* argv[]) { int id; SharedMem *ptr; id = shmget (atoi(argv[1]), 0, 0); if (id == -1){ perror ("child shmget failed"); exit (1); } ptr = shmat (id, (void *) 0, 1023); if (ptr == (void *) -1){ perror ("child shmat failed"); exit (2); } int file, i; struct timeval tv; struct timespec tim, tim2; char Stringtime[4], writing[12]; if ((file = open("prod_green.txt", O_WRONLY)) <= -1) exit(1); for(i = 0; i < 1000; i++){ pthread_mutex_lock(&ptr->lock); while (ptr->count1 == bufferSize && ptr->count2 == bufferSize) while (pthread_cond_wait(&ptr->SpaceAvailable, &ptr->lock) != 0); gettimeofday(&tv, 0); sprintf(writing, "Green %d \\n", tv.tv_usec); tim.tv_sec = 0; tim.tv_nsec = (rand() % 101) * 100; nanosleep(&tim, &tim2); write(file, writing, strlen(writing)); if (ptr->count1 == bufferSize) { strcpy (ptr->Buffer2[ptr->in2], writing); ptr->in2 = (ptr->in2 + 1) % bufferSize; ptr->count2++; } else { strcpy (ptr->Buffer1[ptr->in1], writing); ptr->in1 = (ptr->in1 + 1) % bufferSize; ptr->count1++; } writing[0] = '\\0'; pthread_mutex_unlock(&ptr->lock); pthread_cond_signal(&ptr->ItemAvailable); } pthread_mutex_lock(&ptr->lock2); ptr->end--; pthread_mutex_unlock(&ptr->lock2); close(file); }
1
#include <pthread.h> char name; char target; int gen; pthread_mutex_t *my_mutex; pthread_cond_t *my_cond; int *my_health; pthread_mutex_t *target_mutex; pthread_cond_t *target_cond; int *target_health; }thread_arg_t; char name; char target; int gen; int *exit_flag; pthread_mutex_t *target_mutex; pthread_cond_t *target_cond; int *target_health; pthread_mutex_t *exit_mutex; }shooter_arg_t; pthread_mutex_t A_health_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t A_cond = PTHREAD_COND_INITIALIZER; int A_health = 5; pthread_mutex_t B_health_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t B_cond = PTHREAD_COND_INITIALIZER; int B_health = 5; pthread_attr_t attr; thread_arg_t A_arg = {'A', 'B', 1, &A_health_mutex, &A_cond, &A_health, &B_health_mutex, &B_cond, &B_health}; thread_arg_t B_arg = {'B', 'A', 1, &B_health_mutex, &B_cond, &B_health, &A_health_mutex, &A_cond, &A_health}; void* thread_body(void* arg) { thread_arg_t *info = (thread_arg_t*) arg; pthread_t child, shooter; int exit_flag = 0; pthread_mutex_t exit_mutex; int health_save = 5; int num = 0; pthread_mutex_init(&exit_mutex, 0); shooter_arg_t shooter_arg = {info->name, info->target, info->gen, &exit_flag, info->target_mutex, info->target_cond, info->target_health, &exit_mutex}; while(1) { pthread_mutex_lock(info->my_mutex); if(*info->my_health != health_save) { health_save = *info->my_health; if(*info->my_health == 0) { pthread_mutex_unlock(info->my_mutex); break; } } pthread_mutex_unlock(info->my_mutex); pthread_mutex_lock(info->target_mutex); if(*info->target_health) { num++; (*info->target_health)--; } pthread_mutex_unlock(info->target_mutex); } pthread_mutex_lock(info->my_mutex); if(info->gen < 2) { *info->my_health = 5; info->gen++; pthread_create(&child, &attr, thread_body, (void*)info); pthread_mutex_unlock(info->my_mutex); pthread_exit(0); } pthread_mutex_unlock(info->my_mutex); exit(0); } int main() { pthread_t threads[2]; printf("Main thread starting...\\n"); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&threads[0], &attr, thread_body, (void*)(&A_arg)); pthread_create(&threads[1], &attr, thread_body, (void*)(&B_arg)); printf("Main thread exiting...\\n"); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t thread_cond_var = PTHREAD_COND_INITIALIZER; int counter = 1; void wait_on_cond_var (void) { pthread_mutex_lock (&cond_mutex); pthread_cond_wait(&thread_cond_var, &cond_mutex); pthread_mutex_unlock (&cond_mutex); } void signal_on_cond_var (void) { pthread_mutex_lock (&cond_mutex); pthread_cond_signal(&thread_cond_var); pthread_mutex_unlock (&cond_mutex); } void *print_odd (void *data) { int i = 1; while (i <= 25) { while (counter != i) { wait_on_cond_var (); } printf ("odd %d\\n", i); i += 2; ++counter; signal_on_cond_var (); } pthread_exit (0); } void *print_even (void *data) { int i = 2; while (i <= 25) { while (counter != i) { wait_on_cond_var (); } printf ("even %d\\n", i); i += 2; ++counter; signal_on_cond_var (); } pthread_exit (0); } int main (int argc, char *argv[]) { pthread_t odd_thread, even_thread; printf ("Printing Numbers\\n"); if (pthread_create (&even_thread, 0, print_even, 0) != 0) { printf ("Can't print numbers. Sorry ;-)\\n"); exit (-1); } if (pthread_create (&odd_thread, 0, print_odd, 0) != 0) { printf ("Can't print numbers. Sorry ;-)\\n"); exit (-1); } pthread_join (odd_thread, 0); pthread_join (even_thread, 0); printf ("We are done! bye.\\n"); return 0; }
1
#include <pthread.h> void *do_one_thing(void *); void *do_another_thing(void *); void do_wrap_up(int, int); int r1 = 0, r2 = 0, r3 = 0; pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER; extern int main(int argc, char **argv) { pthread_t thread1, thread2; if (argc > 1) r3 = atoi(argv[1]); if (pthread_create(&thread1, 0, do_one_thing, (void *) &r1) != 0) perror("pthread_create"),exit(1); if (pthread_create(&thread2, 0, do_another_thing, (void *) &r2) != 0) perror("pthread_create"),exit(1); if (pthread_join(thread1, 0) != 0) perror("pthread_join"), exit(1); if (pthread_join(thread2, 0) != 0) perror("pthread_join"), exit(1); do_wrap_up(r1, r2); return 0; } void *do_one_thing(void *pnum_times) { int i, j, x; pthread_mutex_lock(&r3_mutex); if(r3 > 0) { x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4; i++) { printf("doing one thing\\n"); for (j = 0; j < 10000; j++) x = x + i; (*(int *)pnum_times)++; } return(0); } void *do_another_thing(void *pnum_times) { int i, j, x; pthread_mutex_lock(&r3_mutex); if(r3 > 0) { x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4; i++) { printf("doing another \\n"); for (j = 0; j < 10000; j++) x = x + i; (*(int *)pnum_times)++; } return(0); } void do_wrap_up(int one_times, int another_times) { int total; total = one_times + another_times; printf("All done, one thing %d, another %d for a total of %d\\n", one_times, another_times, total); printf("r3 = %d\\n", r3); }
0
#include <pthread.h> pthread_mutex_t theMutex; pthread_cond_t condc, condp; int buffer[10]; int back=0, size=0; void* producer(void* ptr) { int x; while(1==1) { pthread_mutex_lock(&theMutex); printf("Producer Locked\\n"); while(size==10) { printf("Producer waiting\\n"); pthread_cond_wait(&condp, &theMutex); } printf("Producer creating widget %d\\n", back+1); buffer[back]=x; back=back+1; size++; printf("Signaling Consumer\\n"); pthread_cond_signal(&condc); pthread_mutex_unlock(&theMutex); printf("Producer unlocked\\n"); } pthread_exit(0); } void* consumer(void* ptr) { while(1==1) { pthread_mutex_lock(&theMutex); printf("Consumer locked\\n"); while(size==0) { printf("Consumer waiting\\n"); pthread_cond_wait(&condc, &theMutex); } printf("Consumer consuming widget %d\\n", back); buffer[back]=0; back--; size--; printf("Signaling Producer\\n"); pthread_cond_signal(&condp); pthread_mutex_unlock(&theMutex); printf("Consumer unlocked\\n"); } pthread_exit(0); } int main() { pthread_t pro, con; pthread_mutex_init(&theMutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); printf("Creating Consumer\\n"); pthread_create(&con, 0, consumer, 0); printf("Creating Producer\\n"); pthread_create(&pro, 0, producer, 0); printf("Executing Producer\\n"); pthread_join(pro, 0); printf("Executing Consumer\\n"); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&theMutex); return 0; }
1
#include <pthread.h> pthread_cond_t LR_eating; pthread_mutex_t table_mutex; sem_t printStat; char phil_stats[]; int Nphils; void changePrintStates(char state, int idPhil){ sem_wait(&printStat); phil_stats[idPhil] = state; int i; for (i = 0; i < Nphils; ++i) { printf("%c", phil_stats[i]); } printf("\\n"); fflush(stdout); sem_post(&printStat); } void* philosopher(void* arg){ int number = *(int*)(arg); srand(time(0)); while(1){ int rnd = rand() % 10 + 1; sleep(rnd); changePrintStates('H', number); pthread_mutex_lock(&table_mutex); while(phil_stats[(number+Nphils-1)%Nphils] == 69 || phil_stats[(number+1)%Nphils] == 69){ pthread_cond_wait(&LR_eating, &table_mutex); } changePrintStates('E', number); pthread_cond_signal(&LR_eating); pthread_mutex_unlock(&table_mutex); rnd = rand() % 10 + 1; sleep(rnd); changePrintStates('T', number); } } int main(int argc, char **argv){ if(argc < 2){ printf("Numero de filosofos nao especificado."); return 0; } Nphils = atoi(argv[1]); if(Nphils < 1){ printf("Numero de filosofos precisar ser maior/igual a 1."); return 0; } *phil_stats = malloc(sizeof(char)*Nphils); memset(phil_stats, 84, sizeof(char)*Nphils); pthread_t phils[Nphils]; pthread_mutex_init(&table_mutex, 0); sem_init(&printStat, 0, 1); changePrintStates('T', 0); int i; for(i = 0; i < Nphils; ++i){ pthread_create(&phils[i], 0, philosopher, (void*)(&i)); usleep(100); } for (i = 0; i < Nphils; ++i){ pthread_join(phils[i], 0); } return 0; }
0
#include <pthread.h> static int _spoolbuf_slots_open_unlocked(struct spoolbuf_slots_st *spoolslots, struct spoolbdbv_st *spooldb, char *fkey, int *sd, int f_read_unlocked); struct spoolbuf_slots_st *spoolbuf_slots_create(int N){ int status = 0; int i; assert(N > 0); if(N <= 0){ errno = EINVAL; return(0); } struct spoolbuf_slots_st *spoolslots = 0; spoolslots = malloc(sizeof(struct spoolbuf_slots_st)); if(spoolslots == 0){ return(0); } spoolslots->numslots = 0; spoolslots->maxslots = 0; spoolslots->spoolb = 0; spoolslots->status = 0; status = pthread_mutex_init(&spoolslots->mutex, 0); if(status == 0){ status = pthread_cond_init(&spoolslots->cond, 0); if(status != 0) pthread_mutex_destroy(&spoolslots->mutex); } if(status != 0){ free(spoolslots); return(0); } spoolslots->status = calloc(N, sizeof(int)); if(spoolslots->status == 0){ free(spoolslots); return(0); } for(i = 0; i < N; ++i) spoolslots->status[i] = 0; spoolslots->spoolb = calloc(N, sizeof(struct spoolbuf_st*)); if(spoolslots->spoolb == 0){ spoolbuf_slots_destroy(spoolslots); return(0); } for(i = 0; i < N; ++i) spoolslots->spoolb[i] = 0; spoolslots->maxslots = N; for(i = 0; i < N; ++i){ spoolslots->spoolb[i] = spoolbuf_create(); if(spoolslots->spoolb[i] == 0){ status = -1; break; } } if(status != 0){ spoolbuf_slots_destroy(spoolslots); return(0); } return(spoolslots); } void spoolbuf_slots_destroy(struct spoolbuf_slots_st *spoolslots){ int i; assert(spoolslots != 0); pthread_mutex_destroy(&spoolslots->mutex); pthread_cond_destroy(&spoolslots->cond); if(spoolslots->status != 0) free(spoolslots->status); if(spoolslots->spoolb != 0){ for(i = 0; i < spoolslots->maxslots; ++i){ if(spoolslots->spoolb[i] != 0){ spoolbuf_destroy(spoolslots->spoolb[i]); } } free(spoolslots->spoolb); } free(spoolslots); } int spoolbuf_slots_open(struct spoolbuf_slots_st *spoolslots, struct spoolbdbv_st *spooldb, char *fkey, int *sd){ int status = 0; int status1 = 0; status = pthread_mutex_lock(&spoolslots->mutex); if(status != 0) return(status); while((spoolslots->numslots == spoolslots->maxslots) && (status == 0)){ status = pthread_cond_wait(&spoolslots->cond, &spoolslots->mutex); } if(status != 0){ pthread_mutex_unlock(&spoolslots->mutex); return(status); } status = _spoolbuf_slots_open_unlocked(spoolslots, spooldb, fkey, sd, 0); status1 = pthread_mutex_unlock(&spoolslots->mutex); if(status == 0) status = status1; return(status); } int spoolbuf_slots_close(struct spoolbuf_slots_st *spoolslots, int sd){ int status = 0; int status1 = 0; status = pthread_mutex_lock(&spoolslots->mutex); if(status != 0) return(status); (void)spoolbuf_slots_close_unlocked(spoolslots, sd); status = pthread_cond_signal(&spoolslots->cond); status1 = pthread_mutex_unlock(&spoolslots->mutex); if(status == 0) status= status1; return(status); } size_t spoolbuf_slots_read(struct spoolbuf_slots_st *spoolslots, int sd, void *data, size_t size){ return(spoolbuf_read(spoolslots->spoolb[sd], data, size)); } size_t spoolbuf_slots_datasize(struct spoolbuf_slots_st *spoolslots, int sd){ return(spoolbuf_datasize(spoolslots->spoolb[sd])); } static int _spoolbuf_slots_open_unlocked(struct spoolbuf_slots_st *spoolslots, struct spoolbdbv_st *spooldb, char *fkey, int *sd, int f_read_unlocked){ int status = 0; int i; for(i = 0; i < spoolslots->maxslots; ++i){ if(spoolslots->status[i] == 0) break; } assert(i < spoolslots->maxslots); if(f_read_unlocked) status = spoolbdbv_read_unlocked(spooldb, fkey, spoolslots->spoolb[i]); else status = spoolbdbv_read(spooldb, fkey, spoolslots->spoolb[i]); if(status == 0){ *sd = i; ++spoolslots->numslots; spoolslots->status[i] = 1; } return(status); } int spoolbuf_slots_open_unlocked(struct spoolbuf_slots_st *spoolslots, struct spoolbdbv_st *spooldb, char *fkey, int *sd){ return(_spoolbuf_slots_open_unlocked(spoolslots, spooldb, fkey, sd, 1)); } int spoolbuf_slots_close_unlocked(struct spoolbuf_slots_st *spoolslots, int sd){ int status = 0; --spoolslots->numslots; spoolslots->status[sd] = 0; return(status); }
1
#include <pthread.h> static pthread_mutex_t g_mutex; static pthread_mutexattr_t g_attr; static pthread_t g_thread1; static void hold_mutex(int c) { int ret; if (c == 0) { return; } printf("enter hold_mutex [caller %d]\\n", c); ret = pthread_mutex_lock(&g_mutex); hold_mutex(c-1); sleep(1); pthread_mutex_unlock(&g_mutex); printf("leave hold_mutex [caller %d]\\n", c); } static void *thread_callback(void *pdata) { hold_mutex(5); return 0; } int main() { pthread_mutexattr_init(&g_attr); pthread_mutexattr_settype(&g_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&g_mutex, &g_attr); pthread_create(&g_thread1, 0, thread_callback, 0); sleep(1); pthread_mutex_lock(&g_mutex); printf("test\\n"); pthread_mutex_unlock(&g_mutex); pthread_join(g_thread1, 0); pthread_mutex_destroy(&g_mutex); return 0; }
0
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; } struct _scenar { int m_type; int m_pshared; char * descr; } scenarii[] = { {PTHREAD_MUTEX_DEFAULT, 0, "Default mutex"} ,{PTHREAD_MUTEX_NORMAL, 0, "Normal mutex"} ,{PTHREAD_MUTEX_ERRORCHECK, 0, "Errorcheck mutex"} ,{PTHREAD_MUTEX_RECURSIVE, 0, "Recursive mutex"} ,{PTHREAD_MUTEX_DEFAULT, 1, "Pshared mutex"} ,{PTHREAD_MUTEX_NORMAL, 1, "Pshared Normal mutex"} ,{PTHREAD_MUTEX_ERRORCHECK, 1, "Pshared Errorcheck mutex"} ,{PTHREAD_MUTEX_RECURSIVE, 1, "Pshared Recursive mutex"} }; int main (int argc, char * argv[]) { int ret; int i; pthread_mutex_t mtx; pthread_mutexattr_t ma[(sizeof(scenarii)/sizeof(scenarii[0])) + 1]; pthread_mutexattr_t *pma[(sizeof(scenarii)/sizeof(scenarii[0])) + 2]; long pshared; output_init(); pshared = sysconf(_SC_THREAD_PROCESS_SHARED); for (i=0; i<(sizeof(scenarii)/sizeof(scenarii[0])); i++) { ret = pthread_mutexattr_init(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } ret = pthread_mutexattr_settype(&ma[i], scenarii[i].m_type); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set mutex type"); } if ((pshared > 0) && (scenarii[i].m_pshared != 0)) { ret = pthread_mutexattr_setpshared(&ma[i], PTHREAD_PROCESS_SHARED); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set the mutex process-shared"); } } } ret = pthread_mutexattr_init(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } for (i=0; i<(sizeof(scenarii)/sizeof(scenarii[0]))+1; i++) pma[i]=&ma[i]; pma[i] = 0; output("Attributes are ready, proceed to the test\\n"); for (i=0; i<(sizeof(scenarii)/sizeof(scenarii[0])) + 2; i++) { ret = pthread_mutex_init(&mtx, pma[i]); if (ret != 0) { UNRESOLVED(ret, "Failed to init the mutex"); } ret = pthread_mutex_lock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to lock the mutex"); } ret = pthread_mutex_unlock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to unlcok the mutex"); } ret = pthread_mutex_destroy(&mtx); if (ret != 0) { FAILED("Failed to destroy an initialized unlocked mutex"); } } output("Test passed; destroying the test data\\n"); for (i=0; i<(sizeof(scenarii)/sizeof(scenarii[0])) + 1; i++) { ret = pthread_mutexattr_destroy(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy a mutex attribute object"); } } PASSED; }
1
#include <pthread.h> void print_mem(void *ptr, size_t size) { size_t i; char *str; i = 0; str = (char *)ptr; while (i < size && i < 25) { if ((str[i]) > 33 && (int)(str[i]) < 127) ft_putchar(str[i]); else if (str[i] == 0) ft_putchar('0'); else ft_putchar('.'); ft_putchar(' '); i++; } } void print_stuff(void *ptr, size_t size) { ft_atoi_hex(ptr); ft_putstr(" - "); ft_atoi_hex(ptr + size); ft_putstr(" : "); ft_putnbr(size); ft_putstr(" octets"); ft_putchar('\\n'); } void print_type_name(char type) { if (type == TINY) ft_putstr("TINY"); if (type == SMALL) ft_putstr("SMALL"); if (type == LARGE) ft_putstr("LARGE"); } void show_alloc_mem_ex(void) { t_header *header; t_page *page; pthread_mutex_lock(&g_lock); if (g_env.page) { page = g_env.page; while (page) { print_type_name(page->type); ft_putstr(" : "); ft_atoi_hex(page->start); ft_putchar('\\n'); header = page->start; while (header) { if (!header->free) print_stuff_two(header + 1, header->size, header->time); header = header->next; } page = page->next; } } pthread_mutex_unlock(&g_lock); } void show_alloc_mem(void) { t_header *header; t_page *page; pthread_mutex_lock(&g_lock); if (g_env.page) { page = g_env.page; while (page) { print_type_name(page->type); ft_putstr(" : "); ft_atoi_hex(page->start); ft_putchar('\\n'); header = page->start; while (header) { if (!header->free) print_stuff(header + 1, header->size); header = header->next; } page = page->next; } } pthread_mutex_unlock(&g_lock); }
0
#include <pthread.h> void *hilo1(void *p); void *hilo2(void *p); int acabar; char cadena[50]; pthread_mutex_t muti = PTHREAD_MUTEX_INITIALIZER; int main(void) { pthread_t th1; pthread_t th2; int i; int res; void *result; printf("main: Comenzando la primera prueba, sin mutex\\n"); for(i=0; i<50; i++) cadena[i] = '\\0'; acabar = 0; res = pthread_create(&th1, 0, hilo1, 0); res = pthread_create(&th2, 0, hilo2, (void *)0); pthread_join(th1, &result); acabar = 1; pthread_join(th2, &result); printf("main: Comenzando la segunda prueba, con mutex\\n"); for(i=0; i<50; i++) cadena[i] = '\\0'; res = pthread_create(&th1, 0, hilo1, 0); res = pthread_create(&th2, 0, hilo2, (void *)1); pthread_join(th1, &result); acabar = 1; pthread_join(th2, &result); printf("Final del programa\\n"); } void *hilo1(void *arg) { int cnt = 40; char *msg1 = "ABCDEF"; char aux[50]; int nf; struct timespec tim = {0, 1000000L}; nf = 0; while(cnt--) { pthread_mutex_lock(&muti); strcpy(cadena, msg1); nanosleep(&tim, 0); strcpy(aux, cadena); pthread_mutex_unlock(&muti); if(strcmp(aux, msg1) != 0) { printf("hilo1: Error; cadena encontrada: %s\\n", aux); nf++; } } printf("hilo1: %d fallos de %d iteraciones.\\n", nf, 40); return 0; } void *hilo2(void *arg) { char *msg1 = "hilo2 estuvo aqui"; struct timespec tim = {0, 20000000L}; while(!acabar) { if((int)arg) pthread_mutex_lock(&muti); strcpy(cadena, msg1); if((int)arg) pthread_mutex_unlock(&muti); nanosleep(&tim, 0); } }
1
#include <pthread.h> pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER; pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER; void btn_risingInterrupt() { if (digitalRead(GPIO_BTN_PLAY)==HIGH || digitalRead(GPIO_BTN_STOP)==HIGH) { pthread_cond_signal(&fakeCond); } } void* threadPlayBtn( void *thread_arg ){ int bPlay_cnt_clicks, bPlay_cnt_highs, bPlay_cnt_lows; int bStop_cnt_clicks, bStop_cnt_highs, bStop_cnt_lows; bPlay_cnt_clicks = bPlay_cnt_highs = bPlay_cnt_lows = 0; bStop_cnt_clicks = bStop_cnt_highs = bStop_cnt_lows = 0; if (DEBUG) fprintf (stderr, "DEBUG: [btn-thread] -starting\\n"); pinMode(GPIO_BTN_PLAY, INPUT); pullUpDnControl(GPIO_BTN_PLAY, PUD_DOWN); if (wiringPiISR (GPIO_BTN_PLAY, INT_EDGE_RISING, &btn_risingInterrupt) < 0) { mgr_setExitStatus(); fprintf (stderr, "FATAL: HW: Unable to setup ISR: %s\\n", strerror (errno)); return thread_arg; } pinMode(GPIO_BTN_STOP, INPUT); pullUpDnControl(GPIO_BTN_STOP, PUD_DOWN); if (wiringPiISR (GPIO_BTN_STOP, INT_EDGE_RISING, &btn_risingInterrupt) < 0) { mgr_setExitStatus(); fprintf (stderr, "FATAL: HW: Unable to setup ISR: %s\\n", strerror (errno)); return thread_arg; } mgr_unsetWarmingUp(); if (DEBUG) fprintf (stderr, "DEBUG: [btn-thread] +started\\n"); while (!mgr_isExitStatus()) { if (mgr_isWarmingUp()) { delay(500); continue; } if (digitalRead(GPIO_BTN_PLAY)==HIGH) { bPlay_cnt_highs++; bPlay_cnt_lows = 0; } else { if (bPlay_cnt_highs> 2) bPlay_cnt_clicks++; if (bPlay_cnt_clicks) { bPlay_cnt_lows++; if (bPlay_cnt_lows > 20) { if (mgr_isStartPlay() || (mgr_mpd_isPlaying() && !mgr_isStopPlay())) { if (bPlay_cnt_clicks == 1) { if (DEBUG) fprintf(stderr, "DEBUG: HW: <skip> pressed: skip track\\n"); mgr_setSkipFile(); } else { if (DEBUG) fprintf(stderr, "DEBUGL: HD: <skip> double pressed: switch player mode\\n"); mgr_setSkipFolder(); } } else { if (DEBUG) fprintf(stderr, "DEBUG: HW: <skip> pressed: start playing\\n"); mgr_setStartPlay(); } bPlay_cnt_clicks = 0; bPlay_cnt_lows = 0; } } bPlay_cnt_highs = 0; } if (digitalRead(GPIO_BTN_STOP)==HIGH) { bStop_cnt_highs++; bStop_cnt_lows = 0; } else { if (bStop_cnt_highs> 2) bStop_cnt_clicks++; if (bStop_cnt_clicks) { bStop_cnt_lows++; if (bStop_cnt_lows > 20) { if (mgr_isStartPlay() || (mgr_mpd_isPlaying() && !mgr_isStopPlay())) { printf("DEBUG: HW: <skip> pressed: stop playing\\n"); mgr_setStopPlay(); } else { printf("DEBUG: HW: <skip> pressed: start playing\\n"); mgr_setStartPlay(); } bStop_cnt_clicks = 0; bStop_cnt_lows = 0; } } bStop_cnt_highs = 0; } if (bStop_cnt_highs || bPlay_cnt_highs || bStop_cnt_lows || bPlay_cnt_lows) { delay(10); } else { struct timespec timeToWait; memset(&timeToWait, 0, sizeof timeToWait); timeToWait.tv_sec = time(0)+5; timeToWait.tv_nsec = 0; pthread_mutex_lock(&fakeMutex); pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait); pthread_mutex_unlock(&fakeMutex); } } if (DEBUG) fprintf (stderr, "DEBUG: [btn-thread] Thread finished\\n"); return thread_arg; }
0
#include <pthread.h> int numberPhilosophers; int philosopherLocation[10]; int philosopherStatus[10]; int chopstickStatus[10]; pthread_mutex_t chopsticks[10]; int randomwait(int bound) { int wait = rand() % bound; sleep(wait); return wait; } void printPhilosophers () { int i; for (i = 0; i < numberPhilosophers; i++) { if (philosopherStatus[i] == 0) { printf(" ? "); } else if (philosopherStatus[i] == 1) { printf(" \\\\ "); } else if (philosopherStatus[i] == 2) { printf(" \\\\/ "); } } printf("\\n"); } void chopstickGrab (int chopstick){ pthread_mutex_lock(&chopsticks[chopstick]); chopstickStatus[chopstick] += 1; } void chopstickRelease(int chopstick){ pthread_mutex_unlock(&chopsticks[chopstick]); chopstickStatus[chopstick] -= 1; } void ponder (int philosopher) { randomwait(numberPhilosophers); if( rand() % 50 > 20){ philosopherStatus[philosopher] = 1; } } void startEating (int philosopher) { if( rand() % 50 > 20){ chopstickGrab(philosopher); chopstickGrab((philosopher + 1) % numberPhilosophers); philosopherStatus[philosopher] = 2; } randomwait(numberPhilosophers); } void finishEating (int philosopher) { if( rand() % 50 > 20){ chopstickRelease(philosopher); chopstickRelease((philosopher + 1) % numberPhilosophers); philosopherStatus[philosopher] = 0; } } void* transitions(void* philosopher){ int philosopherId = *(int*)philosopher; printPhilosophers(); while(1){ printPhilosophers(); if(philosopherStatus[philosopherId] == 0){ ponder(philosopherId); } else if(philosopherStatus[philosopherId] == 1){ startEating(philosopherId); } else if(philosopherStatus[philosopherId] == 2){ finishEating(philosopherId); } } } int main(int argc, char** argv) { if(argc < 2){ numberPhilosophers = 5; } else if(atoi(argv[1]) == 1){ numberPhilosophers = 5; } else{ numberPhilosophers = atoi(argv[1]); } printf("Initiating Dining Philosophers\\n"); int i; pthread_t philosophers[numberPhilosophers]; for(i = 0 ; i < numberPhilosophers ; i++){ philosopherLocation[i] = i; pthread_mutex_init(&chopsticks[i], 0); pthread_create(&philosophers[i], 0,transitions,&philosopherLocation[i]); } for (i = 0; i < numberPhilosophers; i++) { pthread_join(philosophers[i], 0); } return 0; }
1
#include <pthread.h> char locker = '\\0'; long long counter = 0; int opt_yield=0; int s_test_lock = 0; pthread_mutex_t m_test_mutex; void add(long long* pointer, long long value) { long long sum = *pointer + value; if (opt_yield) pthread_yield(); *pointer = sum; } void* thread_action(void* arg){ int iterations = *(int*)arg; if (locker == 'm'){ for (int i = 0; i < iterations; i++){ pthread_mutex_lock(&m_test_mutex); add(&counter, 1); add(&counter, -1); pthread_mutex_unlock(&m_test_mutex); } } else if(locker=='s'){ for (int i = 0; i < iterations; i++){ while (__sync_lock_test_and_set(&s_test_lock,1)); add(&counter, 1); add(&counter, -1); __sync_lock_release(&s_test_lock); } } else if (locker == 'c'){ for (int i = 0; i < iterations; i++){ int old, sum; do{ old = counter; if (opt_yield) pthread_yield(); sum = old + 1; }while(__sync_val_compare_and_swap(&counter, old, sum)!=old); do{ old = counter; if (opt_yield) pthread_yield(); sum = old - 1; } while (__sync_val_compare_and_swap(&counter, old, sum) != old); } } else if (locker == '\\0'){ for (int i = 0; i < iterations; i++){ add(&counter, 1); add(&counter, -1); } } else fprintf(stderr, "Error: Invalid sync option\\n"); } struct timespec timer; static struct option long_options[] = { { "threads", required_argument, 0, 'a' }, { "iter", required_argument, 0, 'b' }, { "iterations", required_argument, 0, 'b' }, { "yield", required_argument, 0, 'c' }, { "sync", required_argument, 0, 'd' }, {0,0,0,0} }; int main(int argc, char** argv){ pthread_mutex_init(&m_test_mutex, 0); int threads, iterations; threads = iterations = 1; int i = 0; long operations; long per_op; long long time_init, time_finish; char option; while ((option = (char)getopt_long(argc, argv, "", long_options, &i)) != -1){ switch (option){ case 'a': if ((threads = atoi(optarg)) == 0){ fprintf(stderr, "Error: Argument must be positive integer\\n"); } break; case 'b': if ((iterations = atoi(optarg)) == 0){ fprintf(stderr, "Error: Argument must be positive integer\\n"); } break; case 'c': if (atoi(optarg) == 1) opt_yield = 1; break; case 'd': locker = optarg[0]; break; default: fprintf(stderr, "Error: Invalid argument\\n"); break; } } pthread_t *tids = malloc(threads*sizeof(pthread_t)); if (tids == 0){ fprintf(stderr, "Error: memory not allocated\\n"); exit(1); } clock_gettime(CLOCK_MONOTONIC, &timer); time_init = timer.tv_sec * 1000000000 + timer.tv_nsec; for (int a = 0, create_check = 0; a < threads; a++){ create_check = pthread_create(tids + a, 0, thread_action, &iterations); if (create_check){ fprintf(stderr, "Error: unable to create thread\\n"); } } for (int a = 0; a < threads; a++){ pthread_join(tids[a], 0); } clock_gettime(CLOCK_MONOTONIC, &timer); free(tids); time_finish = timer.tv_sec * 1000000000 + timer.tv_nsec - time_init; operations = threads* iterations * 2; fprintf(stdout, "%d threads x %d iterations x (add + subtract) = %ld operations\\n", threads, iterations, operations); if (counter != 0){ fprintf(stderr, "Error: final count = %lld\\n", counter); } fprintf(stdout, "elapsed time: %lld\\n", time_finish); per_op = time_finish / operations; fprintf(stdout, "per operation: %ld\\n", per_op); return 0; }
0
#include <pthread.h> static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER; static unsigned int init_n = 0; int SCE_Init_Utils (FILE *outlog) { int ret = SCE_OK; if (pthread_mutex_lock (&init_mutex) != 0) { SCE_Init_Error (outlog); SCEE_Log (42); SCEE_LogMsg ("failed to lock initialization mutex"); return SCE_ERROR; } init_n++; if (init_n == 1) { SCE_Init_Error (outlog); ret = SCE_ERROR; if (SCE_Init_Mem () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize memory manager"); } else if (SCE_Init_File () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize file manager"); } else if (SCE_Init_NullFS () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize file manager"); } else if (SCE_Init_FileCache () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize cache file manager"); } else if (SCE_Init_Matrix () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize matrices manager"); } else if (SCE_Init_FastList () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize fast lists manager"); } else if (SCE_Init_Media () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize medias manager"); } else if (SCE_Init_Resource () < 0) { SCEE_LogSrc (); SCEE_LogSrcMsg ("can't initialize resources manager"); } else { ret = SCE_OK; } } pthread_mutex_unlock (&init_mutex); if (ret == SCE_ERROR) { SCE_Quit_Utils (); } return ret; } void SCE_Quit_Utils (void) { if (pthread_mutex_lock (&init_mutex) != 0) { SCEE_Log (42); SCEE_LogMsg ("failed to lock initialization mutex"); } else { init_n--; if (init_n < 1) { SCE_Quit_Resource (); SCE_Quit_Media (); SCE_Quit_FastList (); SCE_Quit_FileCache (); SCE_Quit_NullFS (); SCE_Quit_File (); SCE_Quit_Mem (); } pthread_mutex_unlock (&init_mutex); } }
1
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=207); return 0; } void *thread2() { pthread_mutex_lock(&mx); x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; pthread_mutex_unlock(&mx); return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); y=2; return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(800)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(800)]; _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 == (800)) { 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 == (800)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (800)) { 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<(800); 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<(800); 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> void *allocate_tiny(size_t size) { void *block; pthread_mutex_lock(&g_global_lock); if (g_book_keeper.tiny.head == 0) { g_book_keeper.tiny.head = allocate_new_zone(TINY_MAX); divide_zone((void*)&(g_book_keeper.tiny.head), (void*)&(g_book_keeper.tiny.tail), TINY_MAX); } block = allocate_new_block(size, &(g_book_keeper.tiny)); pthread_mutex_unlock(&g_global_lock); return (block); }
0
#include <pthread.h> static char* output_string = 0; static pthread_mutex_t output_lock; static int initialized = 0; static pthread_t thread; static void* query_volume_thread() { if( output_string == 0 ) { output_string = calloc( 128, sizeof(char) ); } while( initialized ) { FILE *acpifp; acpifp = popen("pulseaudio-ctl full-status 2> /dev/null", "r"); if( acpifp == 0 ) { strncpy( output_string, "Volume: --%", 100 ); } else { int volume_level = -1; char mute_string[4]; int muted = 0; fscanf( acpifp, "%d %s", &volume_level, mute_string ); pclose( acpifp ); if( strcmp( mute_string, "yes" ) == 0 ) { muted = 1; } if( volume_level == -1 ) { log_error("Failed to fetch volume level."); } pthread_mutex_lock( &output_lock ); memset( output_string, 0, 128 ); sprintf( output_string, "Volume: %d%%%s", volume_level, muted ? " MUTE" : "" ); pthread_mutex_unlock( &output_lock ); } usleep( 20000 ); } free( output_string ); output_string = 0; return 0; } int volume_init() { if( initialized ) return 0; pthread_mutex_init( &output_lock, 0 ); pthread_create( &thread, 0, &query_volume_thread, 0 ); initialized = 1; return 1; } int volume_destroy() { if( !initialized ) return 0; initialized = 0; pthread_join( thread, 0 ); pthread_mutex_destroy( &output_lock ); return 1; } char* get_volume_information() { if( !initialized ) return 0; char* volume_string = calloc( 128, sizeof(char) ); pthread_mutex_lock( &output_lock ); if( output_string ) { strncpy( volume_string, output_string, 128 -1 ); } pthread_mutex_unlock( &output_lock ); return volume_string; }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; void main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 != 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount1: %d\\n",count); pthread_cond_signal( &condition_var ); if ( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 == 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount2: %d\\n",count); pthread_cond_signal( &condition_var ); if( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } }
0
#include <pthread.h> unsigned int males; unsigned int females; unsigned int total_males; unsigned int total_females; pthread_mutex_t mutex; pthread_cond_t full; } bathroom_t; static bathroom_t shared_bathroom = { .males = 0, .females = 0, .total_males = 0, .total_females = 0, .mutex = PTHREAD_MUTEX_INITIALIZER, .full = PTHREAD_COND_INITIALIZER }; static const char *progname = "unisex"; static void use_bathroom(bathroom_t *bathroom, int ms) { assert(bathroom->females > 0 || bathroom->males > 0); assert((bathroom->females == 0 && bathroom->males < 4) ||(bathroom->males == 0 && bathroom->females < 4)); (void) usleep(1000 * ms); } static void enjoy_live(int ms) { (void) usleep(1000 * ms); } static void* male(void *data) { bathroom_t *bathroom = (bathroom_t *) data; while (1) { enjoy_live(100); pthread_mutex_lock(&bathroom->mutex); while (bathroom->females > 0 || bathroom->males > 2) { pthread_cond_wait(&bathroom->full, &bathroom->mutex); } bathroom->males++; pthread_mutex_unlock(&bathroom->mutex); use_bathroom(bathroom, 10); pthread_mutex_lock(&bathroom->mutex); bathroom->males--; bathroom->total_males++; pthread_cond_broadcast(&bathroom->full); pthread_mutex_unlock(&bathroom->mutex); } return 0; } static void* female(void *data) { bathroom_t *bathroom = (bathroom_t *) data; while (1) { enjoy_live(100); pthread_mutex_lock(&bathroom->mutex); while (bathroom->males > 0 || bathroom->females > 2) { pthread_cond_wait(&bathroom->full, &bathroom->mutex); } bathroom->females++; pthread_mutex_unlock(&bathroom->mutex); use_bathroom(bathroom, 15); pthread_mutex_lock(&bathroom->mutex); bathroom->females--; bathroom->total_females++; pthread_cond_broadcast(&bathroom->full); pthread_mutex_unlock(&bathroom->mutex); } return 0; } static int run(int nm, int nf) { int err, n = nm + nf; pthread_t thread[n]; for (int i = 0; i < n; i++) { err = pthread_create(&thread[i], 0, i < nm ? male : female, &shared_bathroom); if (err) { fprintf(stderr, "%s: %s: unable to create thread %d: %d\\n", progname, __func__, i, err); return 1; } } for (int i = 0; i < n; i++) { if (thread[i]) (void) pthread_join(thread[i], 0); } return 0; } int main(int argc, char *argv[]) { int c, nm = 1, nf = 1; while ((c = getopt(argc, argv, "m:f:h")) >= 0) { switch (c) { case 'm': if ((nm = atoi(optarg)) <= 0) { fprintf(stderr, "number of males must be > 0\\n"); exit(1); } break; case 'f': if ((nf = atoi(optarg)) <= 0) { fprintf(stderr, "number of females must be > 0\\n"); exit(1); } break; case 'h': printf("Usage: %s [-m males] [-f females] [-h]\\n", progname); exit(0); } } return run(nm, nf); }
1
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; FILE *f; int *accesses; struct timeval *recent; int number = 0; int wwidth; int status; void load_time( struct timeval x ) { int i; if( number == wwidth ) { for( i = 0; i < number - 1; i++ ) recent[i] = recent[i + 1]; recent[i] = x; } else { recent[number] = x; number++; } } void *probe( void *num ) { char *url = (char*) malloc(256); unsigned int urlsize = 256; int n = (int) num; accesses[n] = 0; struct timeval time1, time2, timer; char *tmp; pid_t pid; int stat; while(status) { pthread_mutex_lock( &mutex1 ); if( feof(f) ) rewind(f); getline( &url, &urlsize, f ); tmp = strchr(url, '\\n'); if( tmp != 0 ) strcpy(tmp, ""); pthread_mutex_unlock( &mutex1 ); gettimeofday( &time1, 0 ); pid = fork(); if( pid == 0 ) { execlp("wget","wget","--spider","-q",url,0); _exit(0); } else waitpid(pid, &stat, 0); gettimeofday( &time2, 0 ); if( stat == 0 ) { if( time2.tv_usec < time1.tv_usec ) { int nsec = (time1.tv_usec - time2.tv_usec) / 1000000 + 1; time1.tv_usec -= 1000000 * nsec; time1.tv_sec += nsec; } if( time2.tv_usec - time1.tv_usec > 1000000 ) { int nsec = (time2.tv_usec - time1.tv_usec) / 1000000 + 1; time1.tv_usec += 1000000 * nsec; time1.tv_sec -= nsec; } timer.tv_sec = time2.tv_sec - time1.tv_sec; timer.tv_usec = time2.tv_usec - time1.tv_usec; pthread_mutex_lock( &mutex2 ); load_time(timer); accesses[n]++; pthread_mutex_unlock( &mutex2 ); } } return 0; } double findMean() { double mean = 0; int i; for( i = 0; i < number; i++ ) { mean += recent[i].tv_sec; mean += recent[i].tv_usec / 1000000.0; } return mean / number; } double findStdDev() { double stdDev = 0; double mean = findMean(); double num; int i; for( i = 0; i < number; i++ ) { num = recent[i].tv_sec; num += recent[i].tv_usec / 1000000.0; stdDev += ( num - mean) * ( num - mean) / number; } return sqrt(stdDev); } void *reporter( void *num ) { double length = 10.0/((int)num) * 1000000; int i; while(status) { usleep(length); pthread_mutex_lock( &mutex2 ); printf("\\n\\nMean: %lf\\n", findMean()); printf("Std. Deviation: %lf\\n", findStdDev()); printf("\\nThread accesses:\\n"); for( i = 0; i < (int)num; i++ ) printf("Thread %d: %d\\n", i+1, accesses[i]); pthread_mutex_unlock( &mutex2 ); } return 0; } int main( int argc, char *argv[] ) { char check; if( argc != 4 ) { printf("Too few arguments\\n"); printf("Usage: webprobe urlfile wwidth numthreads\\n"); return 0; } status = 1; f = fopen(argv[1], "r"); wwidth = atoi(argv[2]); int numthreads = atoi(argv[3]); pthread_t *id = (pthread_t*) malloc(sizeof(pthread_t)*numthreads); numthreads = numthreads - 1; accesses = (int*) malloc(sizeof(int)*numthreads); recent = (struct timeval*) malloc(sizeof(struct timeval)*numthreads); if( f == 0 ) { printf("File doesn't exist!\\n"); return 0; } int i; for( i = 0; i < numthreads; i++ ) pthread_create( &id[i], 0, probe, (void*) i ); pthread_create( &id[numthreads], 0, reporter, (void*) numthreads ); do { check = getchar(); } while( check != 'q' ); status = 0; for( i = 0; i <= numthreads; i++ ) pthread_join( id[i], 0 ); free(id); free(accesses); free(recent); printf("Bye\\n"); return 0; }
0
#include <pthread.h> int i; { pthread_mutex_t mutex; pthread_cond_t cond; int buf[200000000]; int nput; int next_val; } share_t; share_t share_data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER}; void *produce(void *ptr) { for (;;) { pthread_mutex_lock(&share_data.mutex); if (share_data.next_val >= 200000000) { pthread_mutex_unlock(&share_data.mutex); return 0; } share_data.buf[share_data.next_val] = share_data.nput; share_data.next_val++; share_data.nput++; pthread_cond_signal(&share_data.cond); pthread_mutex_unlock(&share_data.mutex); *(int *)ptr += 1; } } void *consume(void *ptr) { printf("check...\\n"); for (i=0; i<200000000; i++) { pthread_mutex_lock(&share_data.mutex); if (i == share_data.next_val) pthread_cond_wait(&share_data.cond, &share_data.mutex); if (i < share_data.next_val) { pthread_mutex_unlock(&share_data.mutex); if (share_data.buf[i] != i) printf("error: buf[%d] = %d\\n", i, share_data.buf[i]); } } return 0; } int main(int argc, char **argv) { share_data.nput = 0; share_data.next_val = 0; int count[10]; for (int i=0; i<10; i++) count[i] = 0; pthread_t tid_c; pthread_create(&tid_c, 0, consume, 0); pthread_t tid_p[10]; for (int i=0; i<10; i++) { pthread_create(&tid_p[i], 0, produce, &count[i]); } int sum = 0; for (int i=0; i<10; i++) { pthread_join(tid_p[i], 0); printf("thread %d count is %d\\n", i, count[i]); sum += count[i]; } printf("sum = %d\\n", sum); printf("nput = %d,next_val = %d\\n", share_data.nput, share_data.next_val); printf("i = %d\\n", i); pthread_join(tid_c, 0); return 0; }
1
#include <pthread.h> void control_pid_par() { clear_to_color(screen, COL_BG); layout_base("Control PID parameters"); button_set(rectx1, recty1, "Previus"); textout_centre_ex(screen, font, "SET THE GAINS FOR CONTROLLER", sezx/2, d, COL_BUT, BG); button_set(pidx1,pidy1+2*d, "Proportional gain"); button_set(pidx1, pidy1+5*d, "Integral action gain"); button_set(pidx1, pidy1+8*d, "Derivative action gain"); button_set(pidx1, pidy1+11*d, "reference"); } void display_gains(int x, int y, struct controller *PID) { textout_ex(screen,font, "GAINS OF PID CONTORLLER", x-r, y+r+2*d, COL_MOT_REF, BG); sprintf(p, "proportional gain: %.3f", (*PID).KP); textout_ex(screen,font, p, x-r, y+r+d+2*(d+h/2), COL_MOT_REF, BG); sprintf(p, "integral gain: %.3f", (*PID).KI); textout_ex(screen,font, p, x-r, y+r+d+3*(d+h/2), COL_MOT_REF, BG); sprintf(p, "derivative gain: %.3f", (*PID).KD); textout_ex(screen,font, p, x-r, y+r+d+4*(d+h/2), COL_MOT_REF, BG); sprintf(p, "reference: %.3f", (*PID).ref); textout_ex(screen,font, p, x-r, y+r+d+5*(d+h/2), COL_MOT_REF, BG); } void mouse_task_set_PID_par(struct controller *PID, int sem) { if(click_button(pidx1,pidy1+2*d)) { textout_ex(screen, font, "Insert the value of proportional gain (KP): ", pidx1+3.5*l, pidy1+2*d-h/2, COL_MOT_REF, BG); get_string(p, pidx1+9*l, pidy1+2*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*PID).KP); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(pidx1, pidy1+5*d)) { textout_ex(screen, font, "Insert the value of integral gain (KI): ", pidx1+3.5*l, pidy1+5*d-h/2, COL_MOT_REF, BG); get_string(p, pidx1+9*l, pidy1+5*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*PID).KI); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(pidx1, pidy1+8*d)) { textout_ex(screen, font, "Insert the value of derivative gain (KD): ", pidx1+3.5*l, pidy1+8*d-h/2, COL_MOT_REF, BG); get_string(p, pidx1+9*l, pidy1+8*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*PID).KD); pthread_mutex_unlock(&mux_us[sem]); } if(click_button(pidx1, pidy1+11*d)) { textout_ex(screen, font, "Insert the value of reference (rad, rad/sec, Nm): ", pidx1+3.5*l, pidy1+11*d-h/2, COL_MOT_REF, BG); get_string(p, pidx1+9*l, pidy1+11*d-h/2, COL_MOT_REF, BG); pthread_mutex_lock(&mux_us[sem]); sscanf(p, "%f", &(*PID).ref); pthread_mutex_unlock(&mux_us[sem]); pthread_mutex_lock(&mux_page); page = WORK_PAGE; but = 1; pthread_mutex_unlock(&mux_page); layout(); } if(click_button(rectx1, recty1)) { pthread_mutex_lock(&mux_page); page = WORK_PAGE; but = 0; pthread_mutex_unlock(&mux_page); layout(); } }
0
#include <pthread.h> pthread_cond_t Cond_Var; pthread_mutex_t Lock; pthread_t Thread_Id; } Shared_Task; Shared_Task Shared_T; struct TSK Tasks; struct timespec ts; struct timespec nextperiod; pthread_cond_t cv[30]; int firstexec = -1; void Un_Thread(int *i); void Fonc1(int i); int main (int argc, char *argv[]){ int i; int rate; int period; int totalrate; int nbr; int firstdeadline = 32767; int nextexec = -1; int nextdeadline = 32767; int timeexec = 0; int TaskNbr; if (argc != 2){ printf("Usage : %s nombre-de-taches\\n", argv[0]); exit(1); } TaskNbr = atoi(argv[1]); printf("Quels sont le taux d'utilisation et la periode pour chaque tache ?\\n"); for (i = 0; i < TaskNbr; i++){ nbr = scanf("%d %d", &period, &rate); if (nbr != 2){ printf("L'usage est periode-tache taux-activite-tache\\n"); } Tasks.periods[i] = period; Tasks.rate[i] = rate; pthread_cond_init(&cv[i], 0); } for (i = 0; i < TaskNbr; i++){ totalrate += Tasks.rate[i]; } if (totalrate > 100){ printf("Le taux d'utilisation ne peut etre superieur a 100 pourcents\\n"); } pthread_t Threads[TaskNbr]; pthread_cond_init(&Shared_T.Cond_Var, 0); pthread_mutex_init(&Shared_T.Lock, 0); for (i = 0; i < TaskNbr; i++){ int j = i; pthread_create(&Threads[i], 0, (void *) Un_Thread, &j); printf("vient d'etre cree : (0x)%x\\n", (int) Threads[i]); } while (1){ for (i = 0; i < TaskNbr; i++){ if (Tasks.deadlines[i] < firstdeadline && !Tasks.complete[i]){ firstdeadline = Tasks.deadlines[i]; firstexec = i; } } i = 0; while(i != firstdeadline){ if (Tasks.deadlines[i] < nextdeadline && !Tasks.complete[i]){ nextdeadline = Tasks.deadlines[i]; nextexec = i; } } pthread_cond_signal(&cv[firstexec]); clock_gettime(CLOCK_REALTIME, &ts); if ((nextperiod.tv_sec - ts.tv_sec) < Tasks.periods[firstexec]*Tasks.rate[firstexec]*0.01){ ts.tv_sec += (nextperiod.tv_sec - ts.tv_sec); Tasks.completion[firstexec] = ((int) (nextperiod.tv_sec - ts.tv_sec)*100 / Tasks.periods[firstexec]*Tasks.rate[firstexec]); } else { ts.tv_sec += Tasks.periods[firstexec]*Tasks.rate[firstexec]*0.01; Tasks.deadlines[firstexec] += Tasks.periods[firstexec]; Tasks.completion[firstexec] = 100; Tasks.complete[firstexec] = 1; } pthread_mutex_lock(&Shared_T.Lock); pthread_cond_timedwait(&Shared_T.Cond_Var, &Shared_T.Lock, &ts); pthread_mutex_unlock(&Shared_T.Lock); printf("fin du thread (0x)%x\\n", (int) Shared_T.Thread_Id); } return 0; } void Un_Thread(int *i){ int j = *i; pthread_t mon_tid; mon_tid = pthread_self(); printf("Thread (0x)%x : DEBUT\\n", (int) mon_tid); Fonc1(j); printf("Thread (0x)%x : FIN\\n", (int) mon_tid); pthread_exit(0); } void Fonc1(int i){ pthread_mutex_lock(&Shared_T.Lock); while(firstexec != i){ pthread_cond_wait(&cv[i], &Shared_T.Lock); } pthread_mutex_unlock(&Shared_T.Lock); return; }
1
#include <pthread.h> pthread_t threads[ 20 ]; pthread_t chicken_thread; pthread_mutex_t cmutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cvar = PTHREAD_COND_INITIALIZER; int count = 10; int condition = 0; extern int bar(int t, int x); static void * start_chicken(void *arg) { CHICKEN_run(C_toplevel); printf("chicken returned.\\n"); return 0; } static void * start(void *arg) { long i = (long)arg; int j, r; printf("thread %ld waiting...\\n", i); pthread_mutex_lock(&cmutex); while(!condition) pthread_cond_wait(&cvar, &cmutex); printf("thread %ld running ...\\n", i); pthread_mutex_unlock(&cmutex); for(j = 1; j <= count; ++j) { int r, rok; usleep(1000 * 250); printf("thread %ld calling (%ld) ...\\n", i, i + j); r = bar((int)i, i + j); printf("thread %ld call returned: %d\\n", i, r); rok = (i + j) * (i + j); if(r != rok) { printf("ERROR: thread %ld expected %d but got %d\\n", i, rok, r); exit(1); } } printf("thread %ld done.\\n", i); return 0; } int main(int argc, char *argv[]) { int i; int n = 10; pthread_create(&chicken_thread, 0, start_chicken, 0); sleep(2); if(argc > 1) n = atoi(argv[ 1 ]); if(argc > 2) count = atoi(argv[ 2 ]); printf("creating %d threads ...\\n", n); for(i = 0; i < n; ++i) pthread_create(&threads[ i ], 0, start, (void *)(long)i); printf("starting threads ...\\n"); pthread_mutex_lock(&cmutex); condition = 1; pthread_cond_broadcast(&cvar); pthread_mutex_unlock(&cmutex); for(i = 0; i < n; ++i) { printf("waiting for thread %d ...\\n", i); pthread_join(threads[ i ], 0); } printf("done.\\n"); return 0; }
0
#include <pthread.h> void *producer_t(); void *consumer_t(); char buffer[7][14]; int in=0, out=0, count=0; pthread_mutex_t buf_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t empty_slot = PTHREAD_COND_INITIALIZER; pthread_cond_t item_avail = PTHREAD_COND_INITIALIZER; FILE *fp0, *fp1; pthread_t producer, consumer; void main(int argc, char *argv[]){ if( (argv[1]== 0) || argc <3 || argc >3){printf("Correct usage: prog3 infile outfile\\n"); return; } fp0 = fopen(argv[1],"rb"); fp1 = fopen(argv[2],"wb"); int r0, r1; if( (r0= pthread_create(&producer, 0, producer_t, (void*) 0)) ) printf("thread creation failed: 1\\n"); if( (r1= pthread_create(&consumer, 0, consumer_t, (void*) 1)) ) printf("thread creation failed: 2\\n"); pthread_join(producer, 0); pthread_join(consumer, 0); fclose(fp0); fclose(fp1); } void *producer_t(){ char tbuff[14]; strncpy(tbuff, "tmpbuff", sizeof(tbuff)); while(tbuff != 0){ if(fgets(tbuff,14, fp0) != 0){ pthread_mutex_lock(&buf_lock); if(7==count)pthread_cond_wait(&empty_slot, &buf_lock); strncpy(buffer[in], tbuff, 14); count++; in = (in+1)% 7; pthread_cond_signal(&item_avail); pthread_mutex_unlock(&buf_lock); } else pthread_exit(0); } pthread_exit(0); } void *consumer_t(){ printf("in the consumer thread\\n"); char tbuff[14]; strncpy(tbuff, "tmpbuff", sizeof(tbuff)); while(tbuff != 0){ pthread_mutex_lock(&buf_lock); if(count==0) pthread_cond_wait(&item_avail, &buf_lock); strncpy(tbuff, buffer[out], sizeof(tbuff)); out = (out+1) % 7; count--; pthread_cond_signal(&empty_slot); pthread_mutex_unlock(&buf_lock); fputs(tbuff, fp1); if ((feof(fp0) !=0) && (count==0)) pthread_exit(0); } pthread_exit(0); }
1
#include <pthread.h> struct channel g_channel[MAX_CHANNELS]; static pthread_mutex_t channel_hash = PTHREAD_MUTEX_INITIALIZER; void isempty_name_channel(const char *name, struct channel **channel, const char *func_name) { if(name == 0){ complain_error_msg(1, "name is empty from %s!", func_name); exit(1); } if(channel == 0){ complain_error_msg(1, "channel is empty from %s!", func_name); exit(1); } } int log_channel_init(void) { int i = 0; bzero(&g_channel, sizeof(struct channel) * MAX_CHANNELS); for (i = 0; i < MAX_CHANNELS; i++) { g_channel[i].index = i; } return 0; } int log_channel_add(const char *name, struct channel *channel) { isempty_name_channel(name, &channel, "log_channel_add"); return 0; } int log_channel_delete(const char *name, struct channel **channel) { int i = 0; int err = -1; isempty_name_channel(name, channel, "log_channel_delete"); i = (*channel)->index; return err; } int log_channel_get(const char *name, struct channel **channel) { int err = -1; uint64_t keyhash = 0; int i = 0; isempty_name_channel(name, channel, "log_channel_get"); pthread_mutex_lock(&channel_hash); for (i = 0; i < MAX_CHANNELS; i++) { if (g_channel[i].name && (strcmp(name, g_channel[i].name) == 0)) { *channel = &g_channel[i]; pthread_mutex_unlock(&channel_hash); return 0; } } *channel = 0; pthread_mutex_unlock(&channel_hash); return err; } int log_channel_for_each(void (*iterator)(void *, void *, void *), void *user) { int err = 0; int i = 0; pthread_mutex_lock(&channel_hash); for (i = 0; i < MAX_CHANNELS; i++) { if (g_channel[i].state == (cs_INUSE|cs_INEPOLL|cs_HELO)) { iterator(0, &(g_channel[i]), user); } } pthread_mutex_unlock(&channel_hash); return 0; } struct channel *log_channel_new(const char *name) { int i = 0; pthread_mutex_lock(&channel_hash); for (i = 0; i < MAX_CHANNELS; i++) { if (g_channel[i].state == 0) { g_channel[i].state |= cs_INUSE; g_channel[i].name = strdup(name); pthread_mutex_unlock(&channel_hash); return &g_channel[i]; } } pthread_mutex_unlock(&channel_hash); return 0; } void log_channel_free(struct channel *c) { if (c->name) { free(c->name); c->name = 0; } c->state = 0; }
0
#include <pthread.h> void *calculate_frame(void *unused) { while (1) { usleep(dt * 1000000); if (paused()) continue; if (game_end_flag) break; pthread_mutex_lock(&run_yield); capture_passive_mouse_input(); apply_thrust(1); process_motion(1); process_asteroid_motion(1); process_deleted_ast(); process_torpedo_motion(1); process_torpedo_trails(); process_explosion(); process_dust(); process_shield(); process_sound(); ++ticks; pthread_mutex_unlock(&run_yield); } return 0; } void capture_passive_mouse_input(void) { if (paused()) return; if (mouse_roty_flag) turn_abouty(75.0 * mouse_yprop); if (mouse_rotx_flag) turn_aboutx(75.0 * mouse_xprop); if (keyb_rotx_scalar != 0) { turn_aboutx(75.0 * KEYB_BASE_ROT_SCALE * keyb_rotx_scalar); decay_keyb_rotx_scalar(); } if (keyb_roty_scalar != 0) { turn_abouty(75.0 * KEYB_BASE_ROT_SCALE * keyb_roty_scalar); decay_keyb_roty_scalar(); } if (keyb_rotz_scalar != 0) { turn_aboutz(75.0 * KEYB_BASE_ROT_SCALE * keyb_rotz_scalar); decay_keyb_rotz_scalar(); } return; }
1
#include <pthread.h> pthread_mutex_t mutex_oeb; uint64_t get_48(uint32_t addr_low, uint32_t addr_mid, uint32_t addr_high) { uint16_t low = inw(addr_low); uint32_t mid = inw(addr_mid); uint64_t high = inw(addr_high); return (high << 32) + (mid << 16) + low; } int oeb_init() { if(ioperm(0x380, 0x040, -1) != 0) { fprintf(stderr, "Run with root permissions\\n"); return -1; } pthread_mutex_init(&mutex_oeb, 0); return 0; } void oeb_uninit() { pthread_mutex_destroy(&mutex_oeb); } uint64_t oeb_get_clock() { pthread_mutex_lock(&mutex_oeb); outb(0, 0x380); uint64_t result = get_48(0x384, 0x386, 0x388); pthread_mutex_unlock(&mutex_oeb); return result; } void oeb_set_clock(uint64_t value) { pthread_mutex_lock(&mutex_oeb); outw(value & 0xFFFF, 0x3B0); outw((value >> 16) & 0xFFFF, 0x3B2); outw((value >> 32) & 0xFFFF, 0x3B4); pthread_mutex_unlock(&mutex_oeb); } uint64_t oeb_get_irs() { pthread_mutex_lock(&mutex_oeb); outb(0, 0x390); uint64_t result = get_48(0x390, 0x392, 0x394); pthread_mutex_unlock(&mutex_oeb); return result; } uint64_t oeb_get_pyc() { pthread_mutex_lock(&mutex_oeb); outb(0, 0x396); uint64_t result = get_48(0x396, 0x398, 0x39A); pthread_mutex_unlock(&mutex_oeb); return result; } uint64_t oeb_get_rc() { pthread_mutex_lock(&mutex_oeb); outb(0, 0x39C); uint64_t result = get_48(0x39C, 0x39E, 0x3A0); pthread_mutex_unlock(&mutex_oeb); return result; }
0
#include <pthread.h> static void node_unlink (struct node *node, struct ftpfs *fs) { struct netnode *nn = node->nn; if (nn->ncache_next) nn->ncache_next->nn->ncache_prev = nn->ncache_prev; if (nn->ncache_prev) nn->ncache_prev->nn->ncache_next = nn->ncache_next; if (fs->node_cache_mru == node) fs->node_cache_mru = nn->ncache_next; if (fs->node_cache_lru == node) fs->node_cache_lru = nn->ncache_prev; nn->ncache_next = 0; nn->ncache_prev = 0; fs->node_cache_len--; } void ftpfs_cache_node (struct node *node) { struct netnode *nn = node->nn; struct ftpfs *fs = nn->fs; pthread_mutex_lock (&fs->node_cache_lock); if (fs->params.node_cache_max > 0 || fs->node_cache_len > 0) { if (fs->node_cache_mru != node) { if (nn->ncache_next || nn->ncache_prev) node_unlink (node, fs); else netfs_nref (node); nn->ncache_next = fs->node_cache_mru; nn->ncache_prev = 0; if (fs->node_cache_mru) fs->node_cache_mru->nn->ncache_prev = node; if (! fs->node_cache_lru) fs->node_cache_lru = node; fs->node_cache_mru = node; fs->node_cache_len++; } while (fs->node_cache_len > fs->params.node_cache_max) { struct node *lru = fs->node_cache_lru; node_unlink (lru, fs); netfs_nrele (lru); } } pthread_mutex_unlock (&fs->node_cache_lock); }
1
#include <pthread.h> pthread_mutex_t func1_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_spinlock_t func2_mutex; pthread_rwlock_t func34_mutex = PTHREAD_RWLOCK_INITIALIZER; void *pthread_func1(void *unused) { pthread_mutex_lock(&func1_mutex); printf("Func1 mutex lock.\\n"); pthread_mutex_unlock(&func1_mutex); } void *pthread_func2(void *unused) { pthread_spin_lock(&func2_mutex); printf("Func2 mutex lock.\\n"); pthread_spin_unlock(&func2_mutex); } void *pthread_func3(void *unused) { pthread_rwlock_wrlock(&func34_mutex); printf("Func3 mutex lock.\\n"); pthread_rwlock_unlock(&func34_mutex); } void *pthread_func4(void *unused) { pthread_rwlock_rdlock(&func34_mutex); printf("Func3 mutex lock.\\n"); pthread_rwlock_unlock(&func34_mutex); } int main() { FILE *fd = fopen("/home/box/main.pid", "w"); if (fd == 0) { printf("Error opening a file: %d\\n", errno); exit(1); } fprintf(fd, "%ld\\n", (long)getpid()); fflush(fd); fclose(fd); pthread_mutex_lock(&func1_mutex); pthread_spin_init(&func2_mutex, PTHREAD_PROCESS_PRIVATE); pthread_spin_lock(&func2_mutex); printf("All mutex locked.\\n"); pthread_t thread_id1, thread_id2, thread_id3, thread_id4; printf("Start thread1.\\n"); pthread_create(&thread_id1, 0, &pthread_func1, 0); printf("Start thread2.\\n"); pthread_create(&thread_id2, 0, &pthread_func2, 0); printf("Start thread3.\\n"); pthread_create(&thread_id3, 0, &pthread_func3, 0); printf("Start thread4.\\n"); pthread_create(&thread_id4, 0, &pthread_func4, 0); pthread_join(thread_id1, 0); printf("Join thread1. Exit.\\n"); pthread_join(thread_id2, 0); printf("Join thread2. Exit.\\n"); pthread_join(thread_id3, 0); printf("Join thread3. Exit.\\n"); pthread_join(thread_id4, 0); printf("Join thread4. Exit.\\n"); return 0; }
0
#include <pthread.h> struct autharg { char username[32], password[32], hostname[32]; char *vp; }; static int numthreads = 32; static pthread_t *threads; static int running = 1; static struct sigaction sigint; static pthread_mutex_t wait_sigint = PTHREAD_MUTEX_INITIALIZER; void sigint_called() { pthread_mutex_unlock(&wait_sigint); } void *auth(void *p) { char errmsg[1024]; int rc; struct autharg *arg; arg = (struct autharg *) p; while(running) { rc = rad_auth_r(arg->username, arg->password, 3, "servers", arg->vp, errmsg); switch(rc) { case 0: fprintf(stderr, "."); break; case 1: fprintf(stderr, "X"); break; default: fprintf(stderr, "Cannot authenticate: %s\\n", errmsg); } } return 0; } int main(int argc, char *argv[]) { int i; struct autharg arg; char vp[32 + 22]; if(argc >= 3 && !strcmp(argv[1], "-n")) { numthreads = atoi(argv[2]); fprintf(stdout, "Using %d thread%s.\\n", numthreads, numthreads > 1 ? "s" : ""); argc -= 2; argv += 2; } if(argc != 3) { fprintf(stdout, "<user> <pw>: "); fscanf(stdin, "%31s %31s", arg.username, arg.password); } else { strncpy(arg.username, argv[1], 31); strncpy(arg.password, argv[2], 31); } gethostname(arg.hostname, 31); snprintf(vp, sizeof(vp), "Calling-Station-ID = %s", arg.hostname); arg.vp = vp; rad_auth_init("dictionary.rfc2865"); pthread_mutex_lock(&wait_sigint); sigint.sa_handler = sigint_called; sigaction(SIGINT, &sigint, 0); threads = malloc(numthreads * sizeof(pthread_t)); if(!threads) { fprintf(stderr, "Failed to allocate memory for threads!\\n"); exit(-1); } for(i = 0; i < numthreads; i++) { if(pthread_create(&threads[i], 0, auth, &arg) == EAGAIN) { fprintf(stderr, "Error spawning thread %d " "(insufficient resources)\\n", i); numthreads = i; } } pthread_mutex_lock(&wait_sigint); running = 0; fprintf(stderr, "\\nCtrl-C caught, waiting for threads to finish...\\n"); for(i = 0; i < numthreads; i++) pthread_join(threads[i], 0); free(threads); fprintf(stderr, "\\nAll done. Exiting.\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int job[2] = {0}; void *t1_handler(void *arg) { long id = (long)arg; int data; int i; while(1){ pthread_mutex_lock(&mutex); while(job[id] == 0){ pthread_cond_wait(&cond, &mutex); } if(job[id] == -1){ pthread_mutex_unlock(&mutex); pthread_exit(0); } data = job[id]; job[id] = 0; pthread_mutex_unlock(&mutex); for(i = 2; i < data; i++){ if((data % i) == 0) break; } if(i == data) printf("%d is a prime %ld %ld\\n", data, id, (long)pthread_self()); } return 0; } void *t5_handler(void *arg) { int i, j; for(i = 0; i < 100000; ){ pthread_mutex_lock(&mutex); for(j = 0; j < 2 && i < 100000; j++){ if(job[j] == 0) job[j] = i++; } pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); } while(1){ pthread_mutex_lock(&mutex); for(j = 0; j < 2; j++){ if(job[j] == 0) job[j] = -1; } pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); pthread_mutex_lock(&mutex); for(j = 0; j < 2; j++){ if(job[j] != -1) break; } pthread_mutex_unlock(&mutex); if(j == 2){ break; } } return 0; } int main(void) { int i; int ret; pthread_t mainthread; pthread_t t[2]; for(i = 0; i < 2; i++){ ret = pthread_create(t + i, 0, t1_handler, (void *)(long)i); if(ret){ perror("create fail\\n"); exit(1); } } pthread_create(&mainthread, 0, t5_handler, t); pthread_join(mainthread, 0); for(i = 0; i < 2; i++){ printf("join %ld\\n", (unsigned long)t[i]); if(pthread_join(t[i], 0) != 0) fprintf(stderr, "error\\n"); } return 0; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } 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) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { 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 and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
1
#include <pthread.h> int PBSD_sig_put( int c, char *jobid, char *signal, char *extend) { int sock; int rc = 0; struct tcp_chan *chan = 0; pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { rc = PBSE_PROTOCOL; return rc; } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_SignalJob, pbs_current_user)) || (rc = encode_DIS_SignalJob(chan, jobid, signal)) || (rc = encode_DIS_ReqExtend(chan, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return (PBSE_PROTOCOL); } if (DIS_tcp_wflush(chan)) { rc = PBSE_PROTOCOL; } pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return rc; } int PBSD_async_sig_put( int c, char *jobid, char *signal, char *extend) { int sock; int rc = 0; struct tcp_chan *chan = 0; pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { rc = PBSE_PROTOCOL; return rc; } else if ((rc = encode_DIS_ReqHdr(chan,PBS_BATCH_SignalJob,pbs_current_user)) || (rc = encode_DIS_SignalJob(chan,jobid,signal)) || (rc = encode_DIS_ReqExtend(chan,extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return (PBSE_PROTOCOL); } pthread_mutex_unlock(connection[c].ch_mutex); if (DIS_tcp_wflush(chan)) { rc = PBSE_PROTOCOL; } DIS_tcp_cleanup(chan); return(rc); }
0
#include <pthread.h> void *start_calculation(void *arg) { pthread_mutex_lock(&lock_vars); info.highwayLenght = 0.0; int i, k = 0; for (i = 0; i < COUNT - 1; i++) { for (k = i + 1; k < COUNT - 1; k++) { float road = distance_between_city(cityCenter[i], cityCenter[k]); if (i == 0 && (k - 1) == i) { info.minDistance.distance = road; info.maxDistance.distance = road; } if ((k - 1) == i) { info.highwayLenght += road; } if (road < info.minDistance.distance) { info.minDistance.cityA = i; info.minDistance.cityB = k; info.minDistance.distance = road; } else if (road > info.maxDistance.distance) { info.maxDistance.cityA = i; info.maxDistance.cityB = k; info.maxDistance.distance = road; } } } info.average = info.highwayLenght / COUNT; pthread_mutex_unlock(&lock_vars); return 0; }
1
#include <pthread.h> struct th_info { int id; }; int buffer; int empty = 1; pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t empty_cond = PTHREAD_COND_INITIALIZER; void make_product(int tid) { pthread_mutex_lock(&buffer_mutex); while (!empty) { pthread_cond_wait(&empty_cond, &buffer_mutex); } int product = rand() % 1000; buffer = product; empty = 0; printf("producer %d produce product %d\\n", tid, product); pthread_cond_signal(&full_cond); pthread_mutex_unlock(&buffer_mutex); } void consume_product(int tid) { pthread_mutex_lock(&buffer_mutex); while (empty) { pthread_cond_wait(&full_cond, &buffer_mutex); } printf("consumer %d cosume product %d\\n", tid, buffer); empty = 1; pthread_cond_signal(&empty_cond); pthread_mutex_unlock(&buffer_mutex); } void *producer(void *arg) { struct th_info *info = (struct th_info *)(arg); printf("producer %d start!\\n", info->id); for (int i = 0; i < 10; i++) { make_product(info->id); } free(arg); return 0; } void *consumer(void *arg) { pthread_detach(pthread_self()); struct th_info *info = (struct th_info *)(arg); printf("consumer %d start!\\n", info->id); while (1) { consume_product(info->id); } free(arg); return 0; } int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "usage: ./lab1 nProducers nConsumers\\n"); return 1; } int nProducers = atoi(argv[1]); int nConsumers = atoi(argv[2]); if (!(nProducers > 0 && nConsumers > 0)) { fprintf(stderr, "nProducers and nConsumers must be greater than zero\\n"); return 2; } pthread_t *ths = malloc(sizeof(pthread_t) * nProducers); for (int i = 0; i < nProducers; i++) { struct th_info *info = malloc(sizeof(struct th_info)); info->id = i; int err = pthread_create(ths + i, 0, producer, info); if (err < 0) { fprintf(stderr, "pthread_create error: %s\\n", strerror(errno)); return 3; } } for (int i = 0; i < nConsumers; i++) { struct th_info *info = malloc(sizeof(struct th_info)); info->id = i; pthread_t th; int err = pthread_create(&th, 0, consumer, info); if (err < 0) { fprintf(stderr, "pthread_create error: %s\\n", strerror(errno)); return 4; } } for (int i = 0; i < nProducers; i++) { pthread_join(ths[i], 0); } free(ths); }
0
#include <pthread.h> struct job{ struct job* next; }; struct job* job_queue; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; sem_t job_queue_count; void init_job_queue(){ job_queue = 0; int value; sem_init(&job_queue_count, 0,0); } void* thread_function (void* args){ while(1){ struct job* next_job; sem_wait(&job_queue_count); pthread_mutex_lock (&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock (&job_queue_mutex); printf("value %d\\n", next_job->value); } return 0; } void enqueue_job (int data){ struct job* new_job; new_job = (struct job*) malloc (sizeof(struct job)); new_job.value = 5; pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new_job; sem_post(&job_queue_count); pthread_mutex_unlock(&job_queue_mutex); } int main (){ }
1
#include <pthread.h> double* A; double* B; double produto_escalar = 0; int id; } TArgs; pthread_mutex_t s; void* trabalhador(void* args){ TArgs* arg = (TArgs*) args; int id = arg->id; int inicio, fim, i; double soma; inicio = id*(6/2); fim = inicio + (6/2); if(id == 2 -1 && fim < 6) fim = 6; printf("Thread[%d]: %d a %d\\n", id, inicio, fim); for(i=inicio, soma=0; i<fim; i++){ soma += A[i]*B[i]; } pthread_mutex_lock(&s); produto_escalar += soma; pthread_mutex_unlock(&s); } void imprime_vet(double* A, int n){ int i; for(i=0; i<n; i++){ printf("%.0lf ", A[i]); } printf("\\n"); } int main(){ int i; pthread_t threads[2]; TArgs parametros[2]; srand(time(0)); A = (double*) malloc(sizeof(double)*6); B = (double*) malloc(sizeof(double)*6); for(i=0; i<6; i++){ A[i] = rand() % 10; B[i] = rand() % 10; } for(i=0; i<2; i++){ parametros[i].id = i; pthread_create(&threads[i], 0, trabalhador, (void*)&parametros[i]); } for(i=0; i<2; i++){ pthread_join(threads[i], 0); } printf("A:\\n\\t"); imprime_vet(A, 6); printf("B:\\n\\t"); imprime_vet(B, 6); printf("Produto Escalar: %.2lf\\n", produto_escalar); return 0; }
0
#include <pthread.h> pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t space_available = PTHREAD_COND_INITIALIZER; pthread_cond_t data_available = PTHREAD_COND_INITIALIZER; int b[5]; int size = 0; int front,rear=0; main() { pthread_t producer_thread; pthread_t consumer_thread; void *producer(); void *consumer(); pthread_create(&consumer_thread,0,consumer,0); pthread_create(&producer_thread,0,producer,0); pthread_join(consumer_thread,0); } void add_buffer(int i){ b[rear] = i; rear = (rear+1) % 5; size++; } int get_buffer(){ int v; v = b[front]; front= (front+1) % 5; size--; return v ; } void *producer() { int i = 0; while (1) { pthread_mutex_lock(&region_mutex); if (size == 5) { pthread_cond_wait(&space_available,&region_mutex); } add_buffer(i); pthread_cond_signal(&data_available); pthread_mutex_unlock(&region_mutex); i = i + 1; } pthread_exit(0); } void *consumer() { int i,v; for (i=0;i<20;i++) { pthread_mutex_lock(&region_mutex); if (size == 0) { pthread_cond_wait(&data_available,&region_mutex); } v = get_buffer(); printf("got %d\\n",v); pthread_cond_signal(&space_available); pthread_mutex_unlock(&region_mutex); } pthread_exit(0); }
1
#include <pthread.h> int check[20]={0},tree[20]={-1},lca_ind; pthread_mutex_t mutex; void lca(void* lca_index) { int p = (int)lca_index; while(1) { pthread_mutex_lock(&mutex); if(check[p]==1) { lca_ind = p; pthread_mutex_unlock(&mutex); return; } check[p]=1; p/=2; pthread_mutex_unlock(&mutex); } } int main() { pthread_t t1,t2; int no,i,j,k,a,b,nodea[20],nodeb[20],indexa=1,indexb=1; printf("Enter the no of nodes:"); scanf("%d",&no); for(i=1;i<=no;i++) scanf("%d",&tree[i]); printf("Enter node to be searched for:"); scanf("%d %d",&a,&b); for(i=1;i<=no;i++) { if(tree[i]==a) { nodea[indexa] = i; indexa++; } if(tree[i]==b) { nodeb[indexb] = i; indexb++; } } for(i=1;i<indexa;i++) { for(j=1;j<indexb;j++) { pthread_create(&t1,0,lca,(void*)nodea[i]); pthread_create(&t2,0,lca,(void*)nodeb[j]); pthread_join(t1,0); pthread_join(t2,0); printf("LCA is %d when nodea @ %d and nodeb @ %d\\n",tree[lca_ind],nodea[i],nodeb[j]); for(k=0;k<20;k++) check[k]=0; } } return 0; }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void *producer(void *ptr) { int i; for (i = 1; i <= 1000000000; i++) { pthread_mutex_lock(&the_mutex); while (buffer != 0) pthread_cond_wait(&condp, &the_mutex); buffer = i; printf("\\rprod=%d", i); pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { int i; for (i = 1; i <= 1000000000; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) pthread_cond_wait(&condc, &the_mutex); printf("\\r\\t\\tcons=%d", buffer); buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(void) { pthread_t pro, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(pro, 0); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); return 0; }
1
#include <pthread.h> void *find_png(void *path){ char *file, *file_ext, file_path[1000]; DIR *inDir; struct dirent *inDirent; inDir = opendir(path); if (!inDir) { fprintf(stderr, "Error while searching for png files: invalid file path.\\n"); fprintf(stderr, " Unable to open directory at %s\\n", (char *) path); pthread_exit(0); } while ( (inDirent = readdir(inDir)) ) { file = inDirent->d_name; file_ext = strrchr(file, '.'); if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store") || !file_ext) { continue; } if (!strcmp(file_ext, ".png")) { strcpy(file_path, path); strcat(file_path, "/"); strcat(file_path, file); pthread_mutex_lock(&html_mutex); generate_html(file_path); pthread_mutex_unlock(&html_mutex); } } closedir(inDir); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t sem_mutex; pthread_cond_t sem_cond; unsigned int sem_count; int sem_magic; } sem_t; sem_t *sem_open(const char *pathname, int oflag, ...) { int fd, i, created, save_errno; mode_t mode; va_list ap; sem_t *sem, seminit; struct stat statbuf; unsigned int value; pthread_mutexattr_t mattr; pthread_condattr_t cattr; created = 0; sem = MAP_FAILED; again: if (oflag & O_CREAT) { __builtin_va_start((ap)); mode = __builtin_va_arg((ap)) & ~S_IXUSR; value = __builtin_va_arg((ap)); ; fd = open(pathname, oflag | O_EXCL | O_RDWR, mode | S_IXUSR); if (fd < 0) { if (errno == EEXIST && (oflag & O_EXCL) == 0) { goto exists; } else { return (((sem_t *)(-1))); } } created = 1; bzero(&seminit, sizeof(seminit)); if (write(fd, &seminit, sizeof(seminit)) != sizeof(seminit)) { goto err; } sem = mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (sem == MAP_FAILED) { goto err; } if ( (i = pthread_mutexattr_init(&mattr)) != 0) goto pthreaderr; pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); i = pthread_mutex_init(&sem->sem_mutex, &mattr); pthread_mutexattr_destroy(&mattr); if (i != 0) { goto pthreaderr; } if ( (i = pthread_condattr_init(&cattr)) != 0) { goto pthreaderr; } pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); i = pthread_cond_init(&sem->sem_cond, &cattr); pthread_condattr_destroy(&cattr); if (i != 0) { goto pthreaderr; } if ( (sem->sem_count = value) > sysconf(_SC_SEM_VALUE_MAX)) { errno = EINVAL; goto err; } if (fchmod(fd, mode) == -1) { goto err; } close(fd); sem->sem_magic = 0x67458923; return (sem); } exists: if ( (fd = open(pathname, O_RDWR)) < 0) { if (errno == ENOENT && (oflag & O_CREAT)) goto again; goto err; } sem = mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (sem == MAP_FAILED) { goto err; } for (i = 0; i < 10; i++) { if (stat(pathname, &statbuf) == -1) { if (errno == ENOENT && (oflag & O_CREAT)) { close(fd); goto again; } goto err; } if ( (statbuf.st_mode & S_IXUSR) == 0) { close(fd); sem->sem_magic = 0x67458923; return (sem); } sleep(1); } errno = ETIMEDOUT; goto err; pthreaderr: errno = i; err: save_errno = errno; if (created) unlink(pathname); if (sem != MAP_FAILED) munmap(sem, sizeof(sem_t)); close(fd); errno = save_errno; return (((sem_t *)(-1))); } int sem_post(sem_t *sem) { int n; if (sem->sem_magic != 0x67458923) { errno = EINVAL; return (-1); } if ( (n = pthread_mutex_lock(&sem->sem_mutex)) != 0) { errno = n; return (-1); } if (sem->sem_count == 0) { pthread_cond_signal(&sem->sem_cond); } sem->sem_count++; pthread_mutex_unlock(&sem->sem_mutex); return (0); } int sem_wait(sem_t *sem) { int n; if (sem->sem_magic != 0x67458923) { errno = EINVAL; return (-1); } if ( (n = pthread_mutex_lock(&sem->sem_mutex)) != 0) { errno = n; return (-1); } while (sem->sem_count == 0) { pthread_cond_wait(&sem->sem_cond, &sem->sem_mutex); } sem->sem_count--; pthread_mutex_unlock(&sem->sem_mutex); return (0); } int sem_trywait(sem_t *sem) { int n, rc; if (sem->sem_magic != 0x67458923) { errno = EINVAL; return -1; } if ( (n = pthread_mutex_lock(&sem->sem_mutex)) != 0) { errno = n; return (-1); } if (sem->sem_count > 0) { sem->sem_count--; rc = 0; } else { rc = -1; errno = EAGAIN; } pthread_mutex_unlock(&sem->sem_mutex); return (rc); } int sem_getvalue(sem_t *sem, int *pvalue) { int n; if (sem->sem_magic != 0x67458923) { errno = EINVAL; return (-1); } if ( (n = pthread_mutex_lock(&sem->sem_mutex)) != 0) { errno = n; return (-1); } *pvalue = sem->sem_count; pthread_mutex_unlock(&sem->sem_mutex); return 0; } int sem_close(sem_t *sem) { if (sem->sem_magic != 0x67458923) { errno = EINVAL; return (-1); } if (munmap(sem, sizeof(sem_t)) == -1) { return (-1); } return 0; } int sem_unlink(const char *pathname) { if (unlink(pathname) == -1) { return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s <pathname>\\n", argv[0]); exit(1); } char *pathname = argv[1]; int value = 1; sem_t *sem = sem_open(pathname, O_CREAT | O_RDWR, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), value); sem_getvalue(sem, &value); printf("after sem_open, sem value: %d\\n", value); sem_wait(sem); sem_getvalue(sem, &value); printf("after sem_wait, sem value: %d\\n", value); sem_post(sem); sem_getvalue(sem, &value); printf("after sem_post, sem value: %d\\n", value); sem_close(sem); sem_unlink(pathname); return 0; }
1
#include <pthread.h> int map_minerals = 5000; int minerals = 0; int n = 0; int m = 0; int k = -1; int command_centers_minerals[12] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; pthread_mutex_t mutex_workers; pthread_mutex_t mutex_map_minerals; pthread_mutex_t mutex_minerals; pthread_mutex_t mutex_solders; pthread_mutex_t mutex_command_centers; pthread_mutex_t mutex_command_centers_minerals[12]; void* worker (void) { pthread_mutex_lock(&mutex_workers); n++; pthread_mutex_unlock(&mutex_workers); char* name = "SVC " + (n + 49); int worker_minerals = 0; int i; printf("SCV good to go, sir.\\n"); while (m < 20) { printf("%s", name); printf(" is mining\\n"); pthread_mutex_lock(&mutex_map_minerals); map_minerals -= 8; pthread_mutex_unlock(&mutex_map_minerals); worker_minerals += 8; printf("%s", name); printf(" is transporting minerals\\n"); while (worker_minerals > 0) { if (pthread_mutex_trylock(&mutex_minerals) == 0) { minerals += worker_minerals; worker_minerals = 0; pthread_mutex_unlock(&mutex_minerals); } else { for(i = 0; i <= k;i++) { if (pthread_mutex_trylock(&mutex_command_centers_minerals[i]) == 0) { command_centers_minerals[i] += worker_minerals; worker_minerals = 0; pthread_mutex_unlock(&mutex_command_centers_minerals[i]); break; printf("delivered minerals to Command Center "); printf("%d\\n", (i + 2)); } } } } } } void* command_center (void) { pthread_mutex_lock(&mutex_command_centers); command_centers_minerals[++k] = 0; pthread_mutex_unlock(&mutex_command_centers); if (pthread_mutex_init(&mutex_command_centers_minerals[k], 0) != 0) { perror("Fail to initialize mutex: workers!"); } } void* solder (void) { pthread_mutex_lock(&mutex_solders); m++; pthread_mutex_unlock(&mutex_solders); printf("You wanna piece of me, boy?\\n"); } int return_all_minerals (void) { int all = minerals; int i; for (i = 0; i <= k; i++) { all += command_centers_minerals[i]; } return all; } int main (void) { char command; int all = 0; pthread_t workers[100]; pthread_t solders[20]; pthread_t centers[12]; if (pthread_mutex_init(&mutex_workers, 0) != 0) { perror("Fail to initialize mutex: workers!"); } if (pthread_mutex_init(&mutex_command_centers, 0) != 0) { perror("Fail to initialize mutex: command_center!"); } if (pthread_mutex_init(&mutex_solders, 0) != 0) { perror("Fail to initialize mutex: solders!"); } if (pthread_mutex_init(&mutex_map_minerals, 0) != 0) { perror("Fail to initialize mutex: minerals!"); } while(m < 20) { command = getchar(); if ((command == 'm') || (command == 's') || (command == 'c')) { pthread_mutex_lock(&mutex_minerals); all = return_all_minerals(); } if (command == 'm') { if (all > 50) { minerals -= 50; } } if (command == 's') { if (all > 50) { minerals -= 50; } } if (command == 'c') { if (all > 400) { minerals -= 400; } } } return 0; }
0
#include <pthread.h> { int buffer[10]; pthread_mutex_t mutex; pthread_cond_t notfull; pthread_cond_t notempty; int write_pos; int read_pos; }pc_st; pc_st pc; void init_pc(pc_st *pt) { memset(pt->buffer, 0, sizeof(pt->buffer)); pthread_mutex_init(&pt->mutex, 0); pthread_cond_init(&pt->notfull, 0); pthread_cond_init(&pt->notempty, 0); pt->write_pos = 0; pt->read_pos = 0; } void destroy_pc(pc_st *pt) { memset(pt->buffer, 0, sizeof(pt->buffer)); pthread_mutex_destroy(&pt->mutex); pthread_cond_destroy(&pt->notfull); pthread_cond_destroy(&pt->notempty); pt->write_pos = 0; pt->read_pos = 0; } void *clean_up_put(void *arg) { pthread_mutex_unlock(&pc.mutex); } void put(pc_st *pt, int key) { pthread_mutex_lock(&pt->mutex); if((pt->write_pos + 1) % 10 == pt->read_pos) { pthread_cond_wait(&pt->notfull,&pt->mutex); } pt->buffer[pt->write_pos] = key; pt->write_pos = (pt->write_pos + 1) % 10; pthread_cond_signal(&pt->notempty); pthread_mutex_unlock(&pt->mutex); } int get(pc_st *pt) { int value; pthread_mutex_lock(&pt->mutex); if(pt->read_pos == pt->write_pos) { pthread_cond_wait(&pt->notempty,&pt->mutex); } value = pt->buffer[pt->read_pos]; pt->read_pos = (pt->read_pos + 1) % 10; pthread_cond_signal(&pt->notfull); pthread_mutex_unlock(&pt->mutex); return value; } void* producer(void *arg) { int i; for(i=1; i<=20;++i) { put(&pc,i); } put(&pc,-1); } void* consumer(void *arg) { int value; while(1) { value = get(&pc); if(value == -1) break; printf("value = %d\\n",value); } } int main() { init_pc(&pc); pthread_t pro_id, con_id; pthread_create(&pro_id, 0, producer, 0); pthread_create(&con_id, 0, consumer, 0); pthread_join(pro_id,0); pthread_join(con_id,0); destroy_pc(&pc); return 0; }
1
#include <pthread.h> static pthread_mutex_t la_data_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t trigger_la_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t trigger_lagent = PTHREAD_COND_INITIALIZER; struct liveagentt_data *la_data; void send_board_content() { int ret = 0; pthread_mutex_lock(&la_data_mutex); int socket = la_data->socket; pthread_mutex_unlock(&la_data_mutex); board_lock(); char *buffer = get_blackboard(); struct net_board *msg = (struct net_board *)alloc(sizeof(struct net_board)+strlen(buffer)); memcpy(msg->content, buffer, strlen(buffer)); msg->header.type = m_board; msg->header.length = htons(strlen(buffer)); printf("Board-Content send. Size: %li\\n", sizeof(struct net_board)+strlen(buffer)); ret = send(socket, msg, sizeof(struct net_board)+strlen(buffer), 0); if(ret < 0) { perror("send"); fflush(stdout); } board_unlock(); free(msg); } void trigger_liveagent() { pthread_mutex_lock(&trigger_la_mutex); pthread_cond_signal(&trigger_lagent); pthread_mutex_unlock(&trigger_la_mutex); } void *liveagent_handler(void *data) { pthread_mutex_lock(&la_data_mutex); la_data = (struct liveagentt_data *)data; pthread_mutex_unlock(&la_data_mutex); printf("Live-Agent gestartet\\n"); fflush(stdout); struct sigaction sa; sa.sa_handler = send_board_content; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; if (sigaction (SIGALRM, &sa, 0)) { perror("sigaction"); } pthread_mutex_lock(&trigger_la_mutex); while(1) { pthread_cond_wait(&trigger_lagent, &trigger_la_mutex); send_board_content(la_data->socket); } pthread_mutex_unlock(&trigger_la_mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 5) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 5); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[7]; int sorted[7]; void producer () { int i, idx; for (i = 0; i < 7; i++) { idx = findmaxidx (source, 7); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 7; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100*sizeof(double)); b = (double*) malloc (4*100*sizeof(double)); for (i=0; i<100*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h>extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for( i=0; i<((400)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_error(); } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_t Prisoner[64]; pthread_mutex_t mutexlight; pthread_mutex_t mutexstop; int light; int stop; void *prisoner(void *arg) { long tid; tid = (long)arg; if(tid ==0) { int count = 1; for(;count < 64;) { pthread_mutex_lock (&mutexlight); if(light == 1) { light = 0; count ++; } pthread_mutex_unlock(&mutexlight); } pthread_mutex_lock (&mutexstop); stop = 1; pthread_mutex_unlock(&mutexstop); } else { int flag =1, free=0; while( free ==0 ) { pthread_mutex_lock (&mutexlight); if(light == 0 && flag > 0) { flag--; light = 1; } pthread_mutex_unlock(&mutexlight); pthread_mutex_lock (&mutexstop); if(stop == 1) free = 1; pthread_mutex_unlock(&mutexstop); } } pthread_exit(0); } int main (int argc, char *argv[]) { long i = 0; void *status; pthread_attr_t attr;; clock_t t_start, t_end; stop = 0; light = 0; pthread_mutex_init(&mutexlight, 0); pthread_mutex_init(&mutexstop, 0); pthread_attr_init(&attr); t_start = clock(); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(; i<64; i++) pthread_create(&Prisoner[i], 0, prisoner, (void *)i); for (i=0;i<64;i++) pthread_join(Prisoner[i],0); t_end = clock(); printf("time: %fs\\n", (double)(t_end - t_start)/(double)CLOCKS_PER_SEC); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutexlight); pthread_mutex_destroy(&mutexstop); pthread_exit(0); }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc=PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err,signo; for(;;) { err=sigwait(&mask,&signo); if(err!=0) err_exit(err,"sigwait fialed"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag=1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return (0); default: printf("unexpected signal %d\\n",signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask,SIGINT); sigaddset(&mask,SIGQUIT); if((err=pthread_sigmask(SIG_BLOCK,&mask,&oldmask))!=0) err_exit(err,"SIG_BLOCK error"); err=pthread_create(&tid,0,thr_fn,0); if(err!=0) err_exit(err,"can't create thread"); pthread_mutex_lock(&lock); while(quitflag==0) pthread_cond_wait(&waitloc,&lock); pthread_mutex_unlock(&lock); quitflag=0; if(sigprocmask(SIG_SETMASK,&oldmask,0)<0) err_sys("SIG_SETMASK error"); exit(0); }
1
#include <pthread.h> int data = -100; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *writer(void *arg) { int val; pthread_mutex_lock(&mutex1); printf("Enter a value: "); scanf("%d", &val); data = val; pthread_mutex_unlock(&mutex1); return 0; } void *reader(void *arg) { int val; pthread_mutex_lock(&mutex1); if (data == -100) { printf("Value is not provided. Enter a value\\n"); return 0; } val = data; printf("The value is: %d\\n", val); pthread_mutex_unlock(&mutex1); return 0; } int main() { pthread_t t1, t2; while(1) { pthread_create(&t1, 0, writer, 0); pthread_create(&t2, 0, reader, 0); pthread_join(t1, 0); pthread_join(t2, 0); } return 0; }
0
#include <pthread.h> void* producer(void* arg); void* consumer(void* arg); int buffer[100]; int count = 0; int in = -1; int out = -1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t buffer_has_space = PTHREAD_COND_INITIALIZER; pthread_cond_t buffer_has_data = PTHREAD_COND_INITIALIZER; int main(int argc, char* argv[], char* envp[]){ pthread_t threads[2]; pthread_create(&threads[0], 0, producer, 0); pthread_create(&threads[1], 0, consumer, 0); pthread_join(threads[0], 0); pthread_join(threads[1], 0); pthread_cond_destroy(&buffer_has_space); pthread_cond_destroy(&buffer_has_data); pthread_exit(0); printf("main ends!\\n"); return 1; } void* consumer(void* arg) { int i, data = 0; for (int i = 0; i < 100000; i++) { printf(" ** the consumer gets mutex_lock.\\n"); pthread_mutex_lock(&mutex); printf(" ** consumer in the critical section.\\n"); if (count == 0) { printf(" ** consumer blocked, waiting for signal. buffer is empty..\\n"); pthread_cond_wait(&buffer_has_data, &mutex); } out+=1; out = out % 100; data = buffer[out]; count-=1; printf(" ** the consumer throws signal : buffer_has_data.\\n"); pthread_cond_signal(&buffer_has_space); pthread_mutex_unlock(&mutex); printf(" ** the consumer unlocks mutex!\\n"); printf(" the consumer is consuming data : %d\\n", data); printf("\\n\\n"); } } void* producer(void* arg) { int i = 0; for (int i = 0; i < 100000; i++) { printf("the producer is producing the data : %d\\n", i); printf("** the producer gets mutex_lock.\\n"); pthread_mutex_lock(&mutex); printf("** producer in the critical section."); if (count == 100) { printf("** producer blocked, waiting for signal. buffer size is full now.\\n"); pthread_cond_wait(&buffer_has_space, &mutex); } in+=1; in = in % 100; buffer[in] = i; count+=1; printf("** producer throws signal : buffer_has_data.\\n"); pthread_cond_signal(&buffer_has_data); pthread_mutex_unlock(&mutex); printf("** the producer unlocks mutex!\\n"); printf("\\n\\n"); } }
1
#include <pthread.h> int occurenceArray[128]; char buffer[65536]; void printArray(); int i = 0; int sum = 0; pthread_mutex_t lock; int badge; int startOfBuffer; int endOfBuffer; } define_thread_type; void *count(void *param) { pthread_mutex_lock(&lock); define_thread_type *thread_type = (define_thread_type*)param; int countBadge = thread_type->badge; int countStartOfBuffer = thread_type->startOfBuffer; int countEndOfBuffer = thread_type->endOfBuffer; for (int i = countStartOfBuffer; i <= countEndOfBuffer; i++) { for (int j = 0; j < 128; j++) { if (buffer[i] == j){ occurenceArray[j] = occurenceArray[j]+1; } } } pthread_mutex_unlock(&lock); } int main(int argc, char **argv) { if (argc != 2) { printf(" Arguments are wrong\\n\\n\\tUsage: ASCII.c\\n"); return 1; } int i, size; FILE *fp; fp = fopen(argv[1], "r"); fread(buffer,1, (sizeof buffer)-1, fp); for (int i = 0; i < 128; i++){ occurenceArray[i] = 0; } define_thread_type thread_index[8]; pthread_t arrayOfThreads[8]; pthread_attr_t attr; pthread_attr_init(&attr); ssize_t read_bytes = 0; int singleThread = 0; int startingPoint; if (pthread_mutex_init(&lock, 0) !=0) printf("mutex initialization does not work!\\n"); startingPoint = 0; singleThread = ((double)sizeof buffer / 8); for (int tally = 0; tally < 8; tally++) { thread_index[tally].badge = tally; thread_index[tally].startOfBuffer = startingPoint; startingPoint = startingPoint + singleThread; thread_index[tally].endOfBuffer = startingPoint-1; pthread_create(&arrayOfThreads[tally], &attr, count, &thread_index[tally]); } for (int tally = 0; tally < 8; tally++) { pthread_join(arrayOfThreads[tally],0); } pthread_mutex_destroy(&lock); printArray(); } void printArray() { for (int i = 0; i < 33; i++){ printf("%d occurences of 0*%d\\n", occurenceArray[i],i); } for (int i = 32; i < 127; i++) { printf("%d occurences of %c\\n", occurenceArray[i],i); } }
0
#include <pthread.h>extern void __VERIFIER_error(); unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[400]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 400) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 400; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } void *t2(void *arg) { int i; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> const int BUFFER_SIZE = 10; pthread_mutex_t mutex; sem_t sem_empty, sem_full; int g_idx; void ConsumerFunc(void) { volatile int flag = 1; while (flag) { sem_wait(&sem_full); pthread_mutex_lock(&mutex); printf(" Consumer get out of buffer %d\\n", g_idx); if (g_idx == BUFFER_SIZE) flag = 0; sleep(2); pthread_mutex_unlock(&mutex); sem_post(&sem_empty); } } void ProducerFunc(void) { int i; for (i = 1; i <= BUFFER_SIZE; i++) { sem_wait(&sem_empty); pthread_mutex_lock(&mutex); g_idx = i; printf("Producer put into buffer %d\\n", i); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&sem_full); } } int main(void) { pthread_t p_tid, c_tid; g_idx = 0; pthread_mutex_init(&mutex, 0); sem_init(&sem_empty, 0, 1); sem_init(&sem_full, 0, 0); pthread_create(&p_tid, 0, (void*)ProducerFunc, 0); pthread_create(&c_tid, 0, (void*)ConsumerFunc, 0); pthread_join(p_tid, 0); pthread_join(c_tid, 0); return 0; }
0
#include <pthread.h> int npos; pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cvar=PTHREAD_COND_INITIALIZER; int buf[10000000], pos=0, val=0; void *fill(void *); void *verify(void *); int main(int argc, char *argv[]) { int k, nthr, count[100]; pthread_t tidf[100], tidv; if (argc != 3) { printf("Usage: fillver <nr_pos> <nr_thrs>\\n"); return 1; } npos = (atoi(argv[1]))<(10000000) ? (atoi(argv[1])) : (10000000); nthr = (atoi(argv[2]))<(100) ? (atoi(argv[2])) : (100); for (k=0; k<nthr; k++) { count[k] = 0; pthread_create(&tidf[k], 0, fill, &count[k]); } pthread_create(&tidv, 0, verify, 0); for (k=0; k<nthr; k++) { pthread_join(tidf[k], 0); printf("count[%d] = %d\\n", k, count[k]); } pthread_join(tidv, 0); return 0; } void *fill(void *nr) { while (1) { pthread_mutex_lock(&mut); if (pos >= npos) { pthread_mutex_unlock(&mut); return 0; } buf[pos] = val; pos++; val++; pthread_mutex_unlock(&mut); *(int *)nr += 1; } } void *verify(void *arg) { int k; for (k=0; k < npos; k++) { pthread_mutex_lock(&mut); while (k > pos) pthread_cond_wait(&cvar, &mut); if(k < pos) { if (buf[k] != k) { printf("buf[%d] = %d\\n", k, buf[k]); } } pthread_mutex_unlock(&mut); } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int data = 0; void *thread1(void *arg) { pthread_mutex_lock(&mutex); data++; printf ("t1: data %d\\n", data); pthread_mutex_unlock(&mutex); return 0; } void *thread2(void *arg) { pthread_mutex_lock(&mutex); data+=2; printf ("t2: data %d\\n", data); pthread_mutex_unlock(&mutex); return 0; } void *thread3(void *arg) { pthread_mutex_lock(&mutex); printf ("t3: data %d\\n", data); __VERIFIER_assert (0 <= data); __VERIFIER_assert (data <= 10 + 3); pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_mutex_init(&mutex, 0); pthread_t t1, t2, t3; data = __VERIFIER_nondet_int (0, 10); printf ("m: MIN %d MAX %d data %d\\n", 0, 10, data); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t x,wsem; pthread_t tidC[20],tidP[20]; int readcount; void intialize() { pthread_mutex_init(&x,0); pthread_mutex_init(&wsem,0); readcount=0; } void *reader (void *param) { int waittime; int *ind = (int *)param; printf("Reader %d is trying to enter\\n",*ind); pthread_mutex_lock(&x); readcount++; if(readcount==1) pthread_mutex_lock(&wsem); printf("Reader %d is inside\\n",*ind); pthread_mutex_unlock(&x); pthread_mutex_lock(&x); readcount--; if(readcount==0) pthread_mutex_unlock(&wsem); pthread_mutex_unlock(&x); printf("Reader %d is leaving\\n",*ind); } void *writer (void *param) { int waittime; int *ind = (int *)param; waittime=rand() % 3; printf("Writer %d is trying to enter\\n",*ind); pthread_mutex_lock(&wsem); printf("Writer %d is inside\\n",*ind); pthread_mutex_unlock(&wsem); printf("Writer %d is leaving\\n",*ind); } int main() { int n1,n2,i; scanf("%d",&n1); scanf("%d",&n2); for(i=0;i<n1;i++) { int *p = (int*) malloc(sizeof(int)); *p = i+1; pthread_create(&tidP[i],0,reader,p); } for(i=0;i<n2;i++) { int *p = (int*) malloc(sizeof(int)); *p = i+1; pthread_create(&tidC[i],0,writer,p); } for(i=0;i<n1;i++) pthread_join(tidP[i], 0); for(i=0;i<n2;i++) pthread_join(tidC[i], 0); exit(0); }
1
#include <pthread.h> int i = 0; pthread_mutex_t i_mutex; pthread_mutexattr_t i_mattr; void* thread_func1(){ for(int x=0; x < 1000000; x++){ pthread_mutex_lock(&i_mutex); i = i + 1; pthread_mutex_unlock(&i_mutex); } return 0; } void* thread_func2(){ for(int x=0; x < 1000000; x++){ pthread_mutex_lock(&i_mutex); i = i - 1; pthread_mutex_unlock(&i_mutex); } return 0; } int main(){ pthread_mutexattr_init(&i_mattr); pthread_mutexattr_setpshared(&i_mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&i_mutex, &i_mattr); pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, thread_func1, 0); pthread_create(&thread2, 0, thread_func2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&i_mutex); printf("Hey this is i: %i\\n",i); return 0; }
0
#include <pthread.h> pthread_mutex_t ma[4]; pthread_mutex_t mi; void *wa(void *arg) { unsigned id = (unsigned long) arg; pthread_mutex_lock(&ma[id]); pthread_mutex_unlock(&ma[id]); return 0; } void *ra(void *arg) { unsigned id = (unsigned long) arg; pthread_mutex_lock (&mi); pthread_mutex_lock (&ma[id]); pthread_mutex_unlock (&ma[id]); pthread_mutex_unlock (&mi); return 0; } int main() { pthread_t idr[4]; pthread_t idw[4]; pthread_mutex_init(&mi, 0); for (int i = 0; i < 4; i++) { pthread_mutex_init(&ma[i], 0); pthread_create(&idw[i], 0, wa, (void*) (long) i); pthread_create(&idr[i], 0, ra, (void*) (long) i); } pthread_exit (0); for (int i = 0; i < 4; i++) { pthread_join(idw[i],0); pthread_join(idr[i],0); } }
1
#include <pthread.h> size_t words; size_t lines; size_t characters; }statistics; uint8_t filename[20]; statistics values = {0, 0, 0}; struct sigaction sigInit; sigset_t maskSet; FILE *usrFile = 0; sem_t signalThread2; sem_t signalThread3; pthread_mutex_t lockStat; void sig_handler(int signum) { printf("\\nReceived signal %d\\n", signum); if(signum == SIGUSR1) { printf("Start Processing\\n"); sem_post(&signalThread2); } else if(signum == SIGUSR2) { printf("Start Printing Statistics\\n"); sem_post(&signalThread3); } else if(signum == SIGINT) { printf("Received SIGINT"); pthread_mutex_destroy(&lockStat); if(usrFile != 0) fclose(usrFile); exit(0); } } void* statCalc(void* data) { int out; size_t characters; sem_wait(&signalThread2); usrFile = fopen(filename,"a+"); if(usrFile == 0) { return 0; } while( (out = fgetc(usrFile) ) != EOF) { pthread_mutex_lock(&lockStat); values.characters++; if(' ' == out) { values.words++; } else if('\\n' == out) { values.lines++; values.words++; } pthread_mutex_unlock(&lockStat); } printf("\\n"); printf("Success\\n"); fclose(usrFile); usrFile = 0; pthread_exit(0); } void* statPrint(void* data) { sem_wait(&signalThread3); printf("Printing Statistics\\n"); pthread_mutex_lock(&lockStat); printf("Words:%ld\\n",values.words); printf("Lines:%ld\\n",values.lines); printf("Characters:%ld\\n",values.characters); pthread_mutex_unlock(&lockStat); pthread_exit(0); } int main(int argc,char *argv[]) { size_t i; int out; uint16_t error,ret; pthread_t newId, printId; pthread_attr_t newAttr; if((argv+1) != 0) { for(int i=0;argv[1][i] != '\\0';i++) filename[i] = argv[1][i]; } else { printf("Please pass filename as arguments\\n"); return -1; } sigInit.sa_handler = sig_handler; sigemptyset(&sigInit.sa_mask); sigaction(SIGUSR1, &sigInit, 0); sigaction(SIGUSR2, &sigInit, 0); sigaction(SIGINT, &sigInit, 0); if(sem_init(&signalThread2, 0, 0) != 0) { printf("Semaphore signalThread2 Init failed\\n"); } if(sem_init(&signalThread3, 0, 0) != 0) { printf("Semaphore signalThread3 Init failed\\n"); } pthread_mutex_init(&lockStat,0); error = pthread_attr_init(&newAttr); if(error != 0) { printf("Failed in pthread_attr_init\\n"); return -1; } usrFile = fopen(filename,"w"); if(usrFile == 0) { return -1; } for(i=0;out != '\\n';i++) { scanf("%c", (char *)&out); fputc(out , usrFile); } fclose(usrFile); usrFile = 0; printf("Creating Stat Calculation Thread\\n"); error = pthread_create(&newId, &newAttr, &statCalc, (void*)0); if(error != 0) { printf("Failed in pthread_create\\n"); return -1; } printf("Creating Stat Printer Thread\\n"); error = pthread_create(&printId, &newAttr, &statPrint, (void*)0); if(error != 0) { printf("Failed in pthread_create\\n"); return -1; } pthread_join(newId,(void*)&ret); pthread_join(printId,(void*)&ret); pthread_attr_destroy(&newAttr); pthread_mutex_destroy(&lockStat); exit(0); }
0
#include <pthread.h> const char plugin_name[] = "OStrich Scheduler plugin"; const char plugin_type[] = "sched/ostrich"; const uint32_t plugin_version = 100; static int plugin_errno = SLURM_SUCCESS; static pthread_t ostrich_thread = 0; static pthread_t backfill_thread = 0; static pthread_mutex_t thread_flag_mutex = PTHREAD_MUTEX_INITIALIZER; int init( void ) { pthread_attr_t attr; verbose("sched: OStrich scheduler plugin loaded"); pthread_mutex_lock( &thread_flag_mutex ); if ( ostrich_thread || backfill_thread ) { debug2("OStrich: scheduler thread already running, " "not starting another"); pthread_mutex_unlock( &thread_flag_mutex ); return SLURM_ERROR; } slurm_attr_init( &attr ); if (pthread_create( &ostrich_thread, &attr, ostrich_agent, 0)) error("OStrich: unable to start OStrich scheduler thread"); if (pthread_create( &backfill_thread, &attr, backfill_agent, 0)) error("OStrich: unable to start backfill scheduler thread"); pthread_mutex_unlock( &thread_flag_mutex ); slurm_attr_destroy( &attr ); return SLURM_SUCCESS; } void fini( void ) { verbose("sched: OStrich scheduler plugin shutting down"); pthread_mutex_lock( &thread_flag_mutex ); if ( ostrich_thread ) { stop_ostrich_agent(); pthread_join(ostrich_thread, 0); ostrich_thread = 0; } if ( backfill_thread ) { stop_backfill_agent(); pthread_join(backfill_thread, 0); backfill_thread = 0; } pthread_mutex_unlock( &thread_flag_mutex ); } int slurm_sched_plugin_reconfig( void ) { ostrich_reconfig(); backfill_reconfig(); return SLURM_SUCCESS; } int slurm_sched_plugin_schedule( void ) { return SLURM_SUCCESS; } int slurm_sched_plugin_newalloc( struct job_record *job_ptr ) { return SLURM_SUCCESS; } int slurm_sched_plugin_freealloc( struct job_record *job_ptr ) { return SLURM_SUCCESS; } uint32_t slurm_sched_plugin_initial_priority( uint32_t last_prio, struct job_record *job_ptr ) { enqueue_new_job(job_ptr); return 0; } void slurm_sched_plugin_job_is_pending( void ) { } void slurm_sched_plugin_partition_change( void ) { ostrich_reconfig(); } int slurm_sched_get_errno( void ) { return plugin_errno; } char *slurm_sched_strerror( int errnum ) { return 0; } void slurm_sched_plugin_requeue( struct job_record *job_ptr, char *reason ) { } char *slurm_sched_get_conf( void ) { return 0; }
1
#include <pthread.h> char *smackfs_mnt = 0; int smackfs_mnt_dirfd = -1; static pthread_mutex_t smackfs_mnt_lock = PTHREAD_MUTEX_INITIALIZER; static int verify_smackfs_mnt(const char *mnt); static int smackfs_exists(void); int init_smackfs_mnt(void) { char *buf = 0; char *startp; char *endp; FILE *fp = 0; size_t len; ssize_t num; int ret = 0; if (smackfs_mnt || verify_smackfs_mnt("/sys/fs/smackfs/") == 0 || verify_smackfs_mnt("/smack") == 0) return 0; if (!smackfs_exists()) return -1; fp = fopen("/proc/mounts", "r"); if (!fp) return -1; __fsetlocking(fp, FSETLOCKING_BYCALLER); while ((num = getline(&buf, &len, fp)) != -1) { startp = strchr(buf, ' '); if (!startp) { ret = -1; break; } startp++; endp = strchr(startp, ' '); if (!endp) { ret = -1; break; } if (!strncmp(endp + 1, "smackfs"" ", strlen("smackfs") + 1)) { *endp = '\\0'; ret = verify_smackfs_mnt(startp); break; } } free(buf); fclose(fp); return ret; } static int verify_smackfs_mnt(const char *mnt) { struct statfs sfbuf; int rc; int fd; fd = open(mnt, O_RDONLY, 0); if (fd < 0) return -1; do { rc = fstatfs(fd, &sfbuf); } while (rc < 0 && errno == EINTR); if (rc == 0) { if ((uint32_t) sfbuf.f_type == (uint32_t) 0x43415d53) { pthread_mutex_lock(&smackfs_mnt_lock); if (smackfs_mnt_dirfd == -1) { smackfs_mnt = strdup(mnt); smackfs_mnt_dirfd = fd; } else { close(fd); } pthread_mutex_unlock(&smackfs_mnt_lock); return 0; } } close(fd); return -1; } static int smackfs_exists(void) { int exists = 0; FILE *fp = 0; char *buf = 0; size_t len; ssize_t num; fp = fopen("/proc/filesystems", "r"); if (!fp) return 1; __fsetlocking(fp, FSETLOCKING_BYCALLER); num = getline(&buf, &len, fp); while (num != -1) { if (strstr(buf, "smackfs")) { exists = 1; break; } num = getline(&buf, &len, fp); } free(buf); fclose(fp); return exists; } static void fini_lib(void) ; static void fini_lib(void) { if (smackfs_mnt_dirfd >= 0) close(smackfs_mnt_dirfd); free(smackfs_mnt); smackfs_mnt = 0; }
0
#include <pthread.h> void register_bank(void *not_used){ pthread_barrier_wait(&threads_creation); int read_register_1, read_register_2, write_register, write_data; while(1){ pthread_mutex_lock(&control_sign); if(!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } pthread_mutex_lock(&mux_regdst_result); if(!mux_regdst_buffer.isUpdated) while(pthread_cond_wait(&mux_regdst_execution_wait, &mux_regdst_result) != 0); pthread_mutex_unlock(&mux_regdst_result); pthread_mutex_lock(&mux_memtoreg_result); if(!mux_memtoreg_buffer.isUpdated) while(pthread_cond_wait(&mux_memtoreg_execution_wait, &mux_memtoreg_result) != 0); pthread_mutex_unlock(&mux_memtoreg_result); read_register_1 = ((separa_rs & ir) >> 21) & 0x0000003f; read_register_2 = ((separa_rt & ir) >> 16) & 0x0000003f; read_data_1 = reg[read_register_1]; read_data_2 = reg[read_register_2]; write_register = mux_regdst_buffer.value; write_data = mux_memtoreg_buffer.value; pthread_barrier_wait(&current_cycle); if ((cs.value & separa_RegWrite) == ativa_RegWrite) reg[write_register] = write_data; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } printf("Hello from main\\n"); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Exit from main\\n"); return 0; exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\\n",counter); pthread_mutex_unlock( &mutex1 ); }
0
#include <pthread.h> int nprod = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;; int fp1(int nprod) { return nprod < 0; } void* prod(void* d) { pb: pthread_mutex_lock(&m); nprod++; pthread_mutex_unlock(&m); pthread_mutex_lock(&m); nprod++; pthread_mutex_unlock(&m); pthread_mutex_lock(&m); nprod++; pthread_mutex_unlock(&m); pthread_mutex_lock(&m); nprod++; pthread_mutex_unlock(&m); pthread_mutex_lock(&m); nprod++; pthread_mutex_unlock(&m); pe:; pthread_exit(0); } void* cons1(void* d) { c1b: while(1) { pthread_mutex_lock(&m); if (nprod >= 1) nprod--; pthread_mutex_unlock(&m); } c1e:; pthread_exit(0); } void* cons2(void* d) { c2b: while(1) { pthread_mutex_lock(&m); if (nprod >= 1) nprod--; pthread_mutex_unlock(&m); } c2e:; pthread_exit(0); } int main(int argc, char** argv) { pthread_t t1, t2, t3; pthread_create(&t1, 0, prod, 0); pthread_create(&t2, 0, cons1, 0); pthread_create(&t3, 0, cons2, 0); return 0; }
1
#include <pthread.h> int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int nondet_int(); int stored_elements[(20)]; _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 == (20)) { 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 == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for(i=0; i<((20)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: ; } void *t2(void *arg) { int i; for(i=0; i<(20); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { goto ERROR; 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)) { goto ERROR; 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; }
0
#include <pthread.h> static int malloc_cnt, free_cnt; void *p; char *sfile; int lineno; } allocrecord; static allocrecord inuse[(65536)]; static int nused = 0; static int nused_max = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int find(void *p, int last) { int high, i, low; for(low=(-1), high=last; high-low > 1; ) { i = (high+low) / 2; if(p <= inuse[i].p) high = i; else low = i; } return(high); } static int p_insert(void *p, char *sfile, int lineno) { int i, retval; if(nused >= (65536)) { retval = -1; goto exit; } if(nused == 0) { inuse[0].p = p; inuse[0].sfile = sfile; inuse[0].lineno = lineno; nused++; retval = 0; goto exit; } i = find(p, nused-1); if(inuse[i].p == p) { retval = 1; goto exit; } if(inuse[i].p < p) { i++; } nused++; if(nused > i+1) memmove(&inuse[i+1] , &inuse[i], (nused-i-1)*sizeof(inuse[0])); inuse[i].p = p; inuse[i].sfile = sfile; inuse[i].lineno = lineno; if(nused > nused_max) nused_max = nused; retval = 0; exit: return retval; } static int p_remove(void *p) { int i, retval; i = find(p, nused); if(inuse[i].p != p) { retval = 1; goto exit; } if(nused > i+1) memmove(&inuse[i], &inuse[i+1], (nused-i-1) * sizeof(inuse[0])); nused--; inuse[nused].p = 0; retval = 0; exit: return retval; } void KadC_list_outstanding_mallocs(int maxentries) { KadC_log("Total malloc's: %d, total free's: %d \\n", malloc_cnt, free_cnt); { int i; KadC_log("Outstanding blocks now: %d all-time high: %d\\n", nused, nused_max); for(i=0; i < nused && i < maxentries; i++) { KadC_log("0x%8lx: alloc'd in %s, line %d\\n", (unsigned long int)inuse[i].p, inuse[i].sfile, inuse[i].lineno); } if(i < nused) KadC_log("(%d additional outstanding blocks are not listed)\\n", nused - i); } } void *KadC_realloc(void *p, size_t size, char *sf, int ln) { int status; pthread_mutex_lock(&mutex); if(p == 0 && size != 0) { malloc_cnt++; p = malloc(size); if(p == 0) { KadC_log("Warning: call to malloc(%d) returned NULL in %s, line %d\\n", size, sf, ln); } status = p_insert(p, sf, ln); if(status != 0){ KadC_log("Fatal: p_insert(%lx, %s, %d) returned NULL in %s, line %d\\n", (unsigned long int)p, sf, ln, "KadCalloc.c", 178); } } else if(p != 0 && size == 0) { status = p_remove(p); if(status != 0) { KadC_log("can't free(%lx): double free? Called in %s, line %d\\n", (unsigned long int)p, sf, ln); assert(status == 0); } free_cnt++; free(p); } else if(p == 0 && size == 0) { KadC_log("Warning: call to malloc(0) or realloc(NULL,0) in %s, line %d\\n", sf, ln); } else { status = p_remove(p); if(status != 0) { KadC_log("can't free(%lx): double free? Called in %s, line %d\\n", (unsigned long int)p, sf, ln); assert(status == 0); } p = realloc(p, size); status = p_insert(p, sf, ln); assert(status == 0); } assert(nused == malloc_cnt - free_cnt); pthread_mutex_unlock(&mutex); return p; } void *KadC_malloc(size_t size, char *sf, int ln) { return KadC_realloc(0, size, sf, ln); } void KadC_free(void *p, char *sf, int ln) { KadC_realloc(p, 0, sf, ln); } void *KadC_calloc(size_t nelem, size_t elsize, char *sf, int ln) { size_t size = nelem*elsize; void *p = KadC_realloc(0, size, sf, ln); if(p != 0) memset(p, 0, size); return p; } char *KadC_strdup(char *s, char *sf, int ln) { char *s1; int len; if(s == 0) return 0; len = strlen(s)+1; s1 = KadC_realloc(0, len, sf, ln); if(s1 != 0) memcpy(s1, s, len); return s1; }
1
#include <pthread.h> struct barrier { int counter; pthread_mutex_t mutex; pthread_cond_t condition; }; static struct barrier my_barrier = { .counter = 0, .mutex = PTHREAD_MUTEX_INITIALIZER, .condition = PTHREAD_COND_INITIALIZER }; unsigned int random_uint(unsigned int max) { float tmp = (float)rand()/(float)32767 * (float)max; return (unsigned int)ceilf(tmp); } void barrier_sync (struct barrier* b) { pthread_mutex_lock(&b->mutex); b->counter++; if (b->counter == 5) { b->counter = 0; pthread_cond_broadcast(&b->condition); } else { pthread_cond_wait(&b->condition, &b->mutex); } pthread_mutex_unlock(&b->mutex); } void* thread (void* param) { unsigned int i; unsigned int* thread_num = (unsigned int*)param; for (i=0; i<5; i++) { sleep(random_uint(10)); barrier_sync(&my_barrier); } pthread_exit(0); } int main (int argc, char** argv) { unsigned int i; pthread_t thread_id[5]; unsigned int thread_num[5]; for (i=0; i<5; i++) { thread_num[i] = i; pthread_create(&thread_id[i], 0, thread, &thread_num[i]); } for (i=0; i<5; i++) { pthread_join(thread_id[i], 0); } return 0; }
0